#!/bin/bash

# 检查并安装包
PACKAGES=("lat" "i386-runtime-base" "i386-runtime-extra")

for package in "${PACKAGES[@]}"; do
    if ! dpkg -s "$package" >/dev/null 2>&1; then
        echo "安装 $package ..."
        sudo apt update
        sudo apt install -y "$package"
    fi
done

# 检查参数是否为空
if [ $# -eq 0 ]; then
    echo "请在脚本后面添加需要重新打包的deb包名。"
    echo "示例: ./repackage.sh package.deb"
    exit 1
fi

# 创建目录并移动deb包
repackaging_dir="/repackaging"
if [ -d "$repackaging_dir" ];then
    echo "$repackaging_dir目录已经存在，正在进行删除"
    sudo rm -rf $repackaging_dir
fi
sudo mkdir -p "$repackaging_dir"
sudo cp "$1" "$repackaging_dir"
cd "$repackaging_dir"

# 解压deb包
filename=$(basename -- "$1")
sudo dpkg-deb -x "$filename" .
sudo dpkg-deb -e "$filename" ./DEBIAN

# 修改control文件
sudo sed -i 's/Architecture: amd64/Architecture: loongarch64/' DEBIAN/control
sudo sed -i 's/Architecture: arm64/Architecture: loongarch64/' DEBIAN/control
sudo sed -i 's/Depends:.*/Depends: lat, i386-runtime-base, i386-runtime-extra/' DEBIAN/control

# 根据系统修改其他相关文件
# 根据需要进行修改，例如添加loongarch架构

# 重新打包
sudo chown root:root . -R
new_package_name=$(echo "$filename" | sed 's/x86/loongarch/; s/amd/loongarch/ ; s/arm/loongarch/')
sudo dpkg-deb -b . $new_package_name

# 删除旧包及其解压文件
sudo find $repackaging_dir ! -name "$new_package_name" -delete

echo "打包完成！您的包位于 $repackaging_dir 目录下."
echo "可以进入该目录 sudo dpkg -i $new_package_name进行安装"
echo "安装完成可以清理打包目录sudo rm -rf $repackaging_dir，以便下次打包."