#!/bin/sh

PCK_PWRSTUDIO=pwrstudio_4.32.6-r0-pss0_cortexa7hf-neon.ipk
PCK_MSMTP=msmtp_1.6.6-r0_cortexa7hf-neon.ipk
PCK_NTP=ntp_4.2.8p10-r0_cortexa7hf-neon.ipk
PCK_NTP_TICKADJ=ntp-tickadj_4.2.8p10-r0_cortexa7hf-neon.ipk
PCK_NTP_DATE=ntpdate_4.2.8p10-r0_cortexa7hf-neon.ipk
PCK_NTP_UTILS=ntp-utils_4.2.8p10-r0_cortexa7hf-neon.ipk
PCK_LIBELF=libelf1_0.170-r0_cortexa7hf-neon.ipk
PCK_IPROUTE2=iproute2_4.11.0-r0-cir1_cortexa7hf-neon.ipk
PCK_SYSTEM_SERVICE=system-service_1.0-r0-cir3_cortexa7hf-neon.ipk
PCK_CONNMAN=connman_1.34-r0-cir11_cortexa7hf-neon.ipk
PCK_NGINX=nginx_1.12.1-r0-cir2_cortexa7hf-neon.ipk
PCK_INITSCRIPTS=initscripts_1.0-r155-cir0_cortexa7hf-neon.ipk

if [ ! -f /tmp/upgrade/$PCK_PWRSTUDIO ]; then
	rm -fr /tmp/upgrade
	exit 2
fi

auto_reset_watchdog &
/etc/init.d/pwrstudio.sh stop
/etc/init.d/system-service.sh stop

if [ -f /usr/share/pwrstudio/allowedResourcesCustom.xcfg ]; then
	mv /usr/share/pwrstudio/allowedResourcesCustom.xcfg /usr/share/pwrstudio/allowedResourcesCustomBackup.xcfg
fi

DOTNET=$(dotnet --info | grep "Version" | sed "s/Version://g" | sed "s/ //g")
if [ "$DOTNET" == "2.2.3" ]; then
	rm -R /opt/dotnet
fi
opkg remove dotnet-runtime &> /mnt/f1/upgrade.log
opkg remove nginx &>> /mnt/f1/upgrade.log
opkg remove pwrstudio &>> /mnt/f1/upgrade.log
opkg remove iproute2 &>> /mnt/f1/upgrade.log
opkg remove libelf1 &>> /mnt/f1/upgrade.log
opkg remove system-service &>> /mnt/f1/upgrade.log

if [ -f /usr/share/pwrstudio/allowedResourcesCustomBackup.xcfg ]; then
	mv /usr/share/pwrstudio/allowedResourcesCustomBackup.xcfg /usr/share/pwrstudio/allowedResourcesCustom.xcfg
fi

opkg install /tmp/upgrade/$PCK_MSMTP &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_NTP_DATE &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_NTP_TICKADJ &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_NTP &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_NTP_UTILS &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_LIBELF &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_IPROUTE2 &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_SYSTEM_SERVICE &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_CONNMAN &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_NGINX &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/$PCK_INITSCRIPTS &>> /mnt/f1/upgrade.log
opkg install /tmp/upgrade/timezones/*.ipk &>> /mnt/f1/upgrade.log

UNAME=$(uname -r)
RELEASE=$(opkg info kernel-$UNAME | grep Version | awk -F"-r" '{print$NF}')
if [ $RELEASE -lt 1 ]; then
	/tmp/upgrade/kernel_images/nand_flash_kernel.sh
	opkg install /tmp/upgrade/kernel_packages/*.ipk &>> /mnt/f1/upgrade.log
fi

opkg install /tmp/upgrade/$PCK_PWRSTUDIO &>> /mnt/f1/upgrade.log

echo 3.6.6 PSS > /etc/version

reboot
