#!/bin/bash

# 检测系统架构
ARCH=$(uname -m)
echo "Detected architecture: $ARCH"

# 检测当前 Debian 系统版本代号
DISTRO_CODE_NAME=$(lsb_release -cs)
if [ -z "$DISTRO_CODE_NAME" ]; then
    echo "Failed to detect system version codename."
    exit 1
fi
echo "Detected system version: $DISTRO_CODE_NAME"

# 如果是 x86_64 架构，则执行安装依赖软件包
if [ "$ARCH" == "x86_64" ]; then
    # 下载并解压 moOde 安装包
    echo "Downloading and extracting moOde installation package..."
    sudo apt install -y unzip && \
    curl -o /tmp/moode.zip https://vgcafe.com/scripts/moode.zip && \
    unzip -d /tmp/ /tmp/moode.zip || { echo "Failed to download or extract moOde package."; exit 1; }
fi

# 如果是arm架构，则移除armbian软件源
#if [[ "$ARCH" =~ ^aarch64$|^armv7l$|^arm.* ]]; then
#        cd /etc/apt/sources.list.d/
#        mv armbian.sources armbian.sources.bak
#        mv armbian-config.sources armbian-config.sources.bak
#        mv debian.sources debian.sources.bak
#        echo "Armbian source list has been backed up." 
#fi

# 1. 替换 Debian 源为清华大学镜像源（自动识别系统版本）
#echo "Replacing Debian sources..."
#sudo tee /etc/apt/sources.list.d/sources.list > /dev/null <<EOF
#deb https://mirrors.tuna.tsinghua.edu.cn/debian/ $DISTRO_CODE_NAME main contrib non-free non-free-firmware
#deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ $DISTRO_CODE_NAME main contrib non-free non-free-firmware
#deb https://mirrors.tuna.tsinghua.edu.cn/debian/ $DISTRO_CODE_NAME-updates main contrib non-free non-free-firmware
#deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ $DISTRO_CODE_NAME-updates main contrib non-free non-free-firmware
#deb https://mirrors.tuna.tsinghua.edu.cn/debian/ $DISTRO_CODE_NAME-backports main contrib non-free non-free-firmware
#deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ $DISTRO_CODE_NAME-backports main contrib non-free non-free-firmware
#deb https://security.debian.org/debian-security $DISTRO_CODE_NAME-security main contrib non-free non-free-firmware
#deb-src https://security.debian.org/debian-security $DISTRO_CODE_NAME-security main contrib non-free non-free-firmware
#EOF
# sudo apt update && apt upgrade -y
sudo apt update

# 2. 添加 moOde 音频播放器源及密钥，并修改相应的 sources.list.d 文件
echo "Adding moOde player source and key..."
cd /tmp
wget -q --show-progress https://dl.cloudsmith.io/public/moodeaudio/m8y/setup.deb.sh
chmod +x setup.deb.sh
./setup.deb.sh
sudo tee /etc/apt/sources.list.d/moodeaudio-m8y.list > /dev/null <<EOF
deb [signed-by=/usr/share/keyrings/moodeaudio-m8y-archive-keyring.gpg] https://dl.cloudsmith.io/public/moodeaudio/m8y/deb/raspbian $DISTRO_CODE_NAME main
deb-src [signed-by=/usr/share/keyrings/moodeaudio-m8y-archive-keyring.gpg] https://dl.cloudsmith.io/public/moodeaudio/m8y/deb/raspbian $DISTRO_CODE_NAME main
EOF

# 3. 添加 upmpdcli 源及密钥（覆盖下载）
echo "Adding upmpdcli source and key..."
case "$ARCH" in
    x86_64)
        echo "Selected platform: x86_64"
        # 添加 x86 平台的 upmpdcli 源及密钥
        wget -q --show-progress -O /usr/share/keyrings/lesbonscomptes.gpg https://www.lesbonscomptes.com/pages/lesbonscomptes.gpg
        wget -q --show-progress -O /etc/apt/sources.list.d/upmpdcli-$DISTRO_CODE_NAME.list https://www.lesbonscomptes.com/upmpdcli/pages/upmpdcli-$DISTRO_CODE_NAME.list
        ;;
    aarch64|armv7l|arm*)
        echo "Selected platform: ARM"
        # 添加 ARM 平台的 upmpdcli 源及密钥
        wget -q --show-progress -O /usr/share/keyrings/lesbonscomptes.gpg https://www.lesbonscomptes.com/pages/lesbonscomptes.gpg
        wget -q --show-progress -O /etc/apt/sources.list.d/upmpdcli-r$DISTRO_CODE_NAME.list https://www.lesbonscomptes.com/upmpdcli/pages/upmpdcli-r$DISTRO_CODE_NAME.list
        # 添加 Raspberry Pi 源
        echo "Adding Raspberry Pi source..."
        cd /usr/share/keyrings
        wget https://archive.raspberrypi.org/debian/raspberrypi.gpg.key
        cd /etc/apt/sources.list.d
        sudo tee raspi.list > /dev/null <<EOF
# /etc/apt/sources.list.d/raspi.list
deb [signed-by=/usr/share/keyrings/raspberrypi.gpg.key] https://mirrors.tuna.tsinghua.edu.cn/raspberrypi/ $DISTRO_CODE_NAME main untested
EOF
        ;;
    *)
        echo "Unsupported architecture: $ARCH"
        exit 1
        ;;
esac

# 4. 更新 APT 缓存并升级现有软件包
echo "Updating APT cache and upgrading packages..."
# sudo apt update && sudo apt upgrade -y
sudo apt update -y

# 5. 安装必要的依赖包 (增加 wireless-tools iw dnsmasq ) 
echo "Installing necessary dependencies..."
#sudo apt install -y network-manager dphys-swapfile alsa-utils wireless-tools iw vim dnsmasq polkitd
sudo apt install -y dphys-swapfile alsa-utils wireless-tools vim dnsmasq polkitd
# 6. 安装依赖软件、虚拟软件包（仅限 x86_64）
if [ "$ARCH" == "x86_64" ]; then
    echo "Installing dependency and virtual packages for x86_64..."
    mkdir -p /tmp/all_packages
    cp -f /tmp/moode_packages/*.deb /tmp/extra/packages/*.deb /tmp/all_packages/ 2>/dev/null || echo "No additional packages found."
    if [ "$(ls -A /tmp/all_packages/*.deb 2>/dev/null)" ]; then
        sudo dpkg -i /tmp/all_packages/*.deb || echo "Error installing some packages. Continuing..."
        sudo apt-get install -f -y || echo "Failed to fix broken dependencies. Continuing..."
    else
        echo "No additional dependency or virtual packages found."
    fi
fi

# 7. 安装前预处理防止无限重启
echo "Pre-processing to prevent infinite reboot..."
mkdir -p /boot/firmware
touch /etc/nftables.conf
touch /etc/X11/Xwrapper.config
mkdir /etc/peppymeter
mkdir /etc/peppyspectrum
touch /etc/peppymeter/config.txt
touch /etc/peppyspectrum/config.txt
useradd mpd

# 8. 安装最新版 moOde 播放器
echo "Installing the latest version of moOde player..."
sudo apt install -y moode-player
sudo apt-get install -f -y
# 9. 如果选择了 arm64 平台，则处理 bluez-firmware 安装错误（如果存在）
#if [[ "$ARCH" =~ ^aarch64$|^armv7l$|^arm.* ]]; then
#    echo "Handling potential bluez-firmware installation errors..."
#    cd /var/cache/apt/archives
#    sudo dpkg -i --force-overwrite ./bluez-firmware*.deb || echo "No bluez-firmware package found or no need to overwrite."
#    sudo apt-get install -f -y
#fi

# 10. 修改/etc/rc.local 解决服务运行错误
echo "Modifying /etc/rc.local to fix service run errors..."
sudo sed -i '1s|^.*|#!/bin/bash|' /etc/rc.local

# 11. 复制修复 cdsp 无法打开 alsa 设备问题（仅限 x86_64 平台）
if [ "$ARCH" == "x86_64" ]; then
    echo "Copying the fix for cdsp unable to open alsa device issue..."
    sudo cp /alsa-lib/libasound_module_pcm_cdsp.so /lib/x86_64-linux-gnu/alsa-lib/libasound_module_pcm_cdsp.so
fi

# 13. 修复缺失的系统信息和音频设置；
#wget https://vgcafe.com/scripts/snd_sys.zip
#sudo unzip snd_sys.zip
#sudo cp snd-config.php /var/www/
#sudo cp sysinfo.sh /var/www/util/sysinfo.sh
#rm -rf snd-config.php sysinfo.sh

# 14. 禁用树莓派升级服务；
sudo systemctl disable rpi-eeprom-update.service
systemctl disable unattended-upgrades
cp /usr/lib/armbian/armbian-apt-updates /usr/lib/armbian/armbian-apt-updates.bak
echo > /usr/lib/armbian/armbian-apt-updates
systemctl stop dphys-swapfile
systemctl disable dphys-swapfile
rm /var/swap


# 15. 增加rootfs 标签
ROOTDEV=$(findmnt -n -o SOURCE /)
e2label $ROOTDEV rootfs

# 16. 修正 `/var/www/daemon/worker.php` 启动错误
sed -i 's|^#!/bin/sh -e$|#!/bin/bash|' /etc/rc.local
ln -sf /usr/bin/python3 /usr/bin/python

# 17. 清理安装文件
echo "Cleaning up..."
sudo apt clean
sudo apt --purge autoremove -y
sudo rm -rf /tmp/all_packages /tmp/extra /tmp/moode_packages /tmp/*.sh


# 18. 提示用户重启系统，并请求确认，默认选项为 Y
echo -n "System will reboot in 10 seconds, press N to cancel: "
read -t 30 -n 1 answer
if [[ $answer =~ ^[Yy]$ ]]; then
    echo "Rebooting now..."
    sudo reboot
else
    echo "No input received or N selected, cancelled reboot by user."
    
fi
