#!/bin/sh

release="/tmp/qow-release.tar.gz"

if [ -r $release ]; then
        echo "Release file $release is already downloaded"
else
        cd /tmp
        wget -q http://packages.wnam.ru/qow/qow-release.tar.gz
        if [ ! -r $release ]; then
                echo "New release cannot be downloaded"
                exit 1
        else
                ls -la $release
        fi
fi

if [ -d /tmp/qow-tmp ]; then
	rm -rf /tmp/qow-tmp
fi

mkdir /tmp/qow-tmp
cd /tmp/qow-tmp
tar zxf $release
nfiles=`ls -1 | wc -l`
if [ $nfiles -lt 20 ]; then
        echo "Release seems to be corrupted"
        exit 2
fi

if [ -x "9994-patch-usbmode-usb-storage-to-support-huawei-e3276" ]; then
	echo "Running huawei e3276 support setup script..."
	. ./9994-patch-usbmode-usb-storage-to-support-huawei-e3276
fi

echo "Stop QoW application..."
/etc/init.d/qow_sensor stop

new_rel_req=`md5sum requirements.txt 2>/dev/null | cut -f 1 -d " "`


oldpid=`ps | grep wnam_async | grep -v grep | cut -d ' ' -f 1`
if [ ! -z $oldpid ]; then
	kill -9 $oldpid
fi

[ ! -d /root/qow ] && mkdir -p /root/qow

[ ! -e /root/qow/.env ] && {
    cp .env-template /root/qow/.env
	fresh=1
}
	
chmod 755 *.init



cd /root/qow
cp .env /tmp/qow-env.bak
old_rel_req=`md5sum requirements.txt 2>/dev/null | cut -f 1 -d " "`

rm -rf *
mv /tmp/qow-tmp/* /tmp/qow-tmp/.env-template .
rm -rf /tmp/qow-tmp/
rm $release
mv cipher.py /usr/lib/python3.*/site-packages/pytube/
chmod +x *.py
chmod +x fft_eval_json
chmod +x qow-upgrade.sh 
ver=`cat version.txt`
ver=${ver//$'\n'/}
echo 'WNAM QoW Sensor v.1 (B1300)' > /tmp/sysinfo/model
echo "New QoW release $ver is installed"
if [ ! -z ${fresh+x} ]; then
	printf "Please install python dependencies then retry:\n\tpip3 install -r requirements.txt\n"
	exit 0
fi

if [[ "$new_rel_req" != "$old_rel_req" ]]; then 
	echo "Upgrade python libraries requirements"
	pip3 install -r requirements.txt
fi

echo "Executing setup script..."
./wnam_setup.py
cp qow_sensor.init /etc/init.d/qow_sensor
/etc/init.d/qow_sensor enable
cp qow_watchdog.init /etc/init.d/qow_watchdog
/etc/init.d/qow_watchdog enable

echo "Start QoW application..."
rm /var/log/wnam_qos*.log
/etc/init.d/qow_sensor restart

echo "copy custom /etc/udhcpc.user..."
chmod +x /root/qow/udhcpc.user
cp /root/qow/udhcpc.user /etc/udhcpc.user
