#!/bin/bash

export EXEC_NAME=update-system
export VERSION_DIR=/usr/local
export UNPACKED_DIR=/
export ARCHIVE_PATH=${VERSION_DIR}/${EXEC_NAME}

mkdir ${VERSION_DIR}/${EXEC_NAME}
wget -P ${VERSION_DIR}/${EXEC_NAME} https://download.repka-pi.ru/repka_os_update/v1.0.21_d13.06.24/update-system.tar.gz
tar -xvf ${VERSION_DIR}/${EXEC_NAME}/${EXEC_NAME}.tar.gz -C ${VERSION_DIR}/${EXEC_NAME}

cp ${VERSION_DIR}/${EXEC_NAME}/${EXEC_NAME}/dtb/* /boot/dtb
rm /boot/spl/*
cp ${VERSION_DIR}/${EXEC_NAME}/${EXEC_NAME}/spl/* /boot/spl
cp ${VERSION_DIR}/${EXEC_NAME}/${EXEC_NAME}/tools/axp.shutdown /usr/lib/systemd/system-shutdown
cp ${VERSION_DIR}/${EXEC_NAME}/${EXEC_NAME}/tools/wifi-bind.sh /usr/local/scripts

export COOLING=$(cat /proc/device-tree/repka-cooling)
export PINOUT=$(cat /proc/device-tree/repka-pinout)
export DTB_POSTFIX=""

if [[ "$COOLING" -eq 1 ]]; then
    DTB_POSTFIX=""
elif [[ "$COOLING" -eq 0 ]]; then
    DTB_POSTFIX="p"
fi

case "$PINOUT" in
    1)
        cp /boot/dtb/sun50i-h5-repka-pi3-v1.4${DTB_POSTFIX}.dtb /boot/sun50i-h5-repka-pi3.dtb ;;
    2)
        cp /boot/dtb/sun50i-h5-repka-pi3-alt-v1.4${DTB_POSTFIX}.dtb /boot/sun50i-h5-repka-pi3.dtb ;;
    3)
        cp /boot/dtb/sun50i-h5-repka-pi3-alt-uart-v1.4${DTB_POSTFIX}.dtb /boot/sun50i-h5-repka-pi3.dtb ;;
    4)
        cp /boot/dtb/sun50i-h5-repka-pi3-alt-i2c2-v1.4${DTB_POSTFIX}.dtb /boot/sun50i-h5-repka-pi3.dtb ;;
    5)
        cp /boot/dtb/sun50i-h5-repka-pi3-alt-pwm-v1.4${DTB_POSTFIX}.dtb /boot/sun50i-h5-repka-pi3.dtb ;;
    6)
        cp /boot/dtb/sun50i-h5-repka-pi3-alt-uart-can-v1.4${DTB_POSTFIX}.dtb /boot/sun50i-h5-repka-pi3.dtb ;;
    *)
        cp /boot/dtb/sun50i-h5-repka-pi3-v1.4${DTB_POSTFIX}.dtb /boot/sun50i-h5-repka-pi3.dtb ;;
esac

whiptail --title  "Обновлено дерево устройств" \
  --msgbox  "Вы обновили дерево устройств!\nОбращаем внимание, что максимальная частота изменилась на 1.368 Ghz\nВы можете изменить необходимую частоту через repka-config\nЧтобы изменения вступили в силу необходимо перезагрузить Repka Pi" 20 60

rm -rf ${VERSION_DIR}/${EXEC_NAME}
