#!/bin/bash

TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")
CURRENT_VERSION=$(grep -a SHIELD_build_version /home/relayup/dev/Shield | sed 's/\$.*//' | sed 's/\.//g')
UPDATE_VERSION=$(grep -a SHIELD_build_version /mnt/usb/update/home/relayup/dev/Shield | sed 's/\$.*//' | sed 's/\.//g')
SHIELD_SERIAL=$(cat /proc/cpuinfo | grep Serial | awk '{print $3}')

if [ "$CURRENT_VERSION" -lt "$UPDATE_VERSION" ];then

    ## Copy update to local storage
    mkdir /home/update/
    cp -r /mnt/usb/update /home/
    
    if [[ $(grep -cw "10_Set=on" /home/relayup/dev/00_saved.cfg) -eq 1 && "$CURRENT_VERSION" -lt "200" ]];then

        NICKNAME=$(grep 13_Set /home/relayup/dev/00_saved.cfg  | cut -d'=' -f2)
        echo "Nickname $NICKNAME" > /home/update/home/relayup/dev/vpn_config.cfg    
        EMAIL=$(grep 14_Set /home/relayup/dev/00_saved.cfg  | cut -d'=' -f2)
        WALLET_ID=$(grep 15_Set /home/relayup/dev/00_saved.cfg  | cut -d'=' -f2)
        echo "ContactInfo $EMAIL @anon: $WALLET_ID"  >> /home/update/home/relayup/dev/vpn_config.cfg
        cat /mnt/usb/update/home/relayup/dev/vpn_config.cfg >> /home/update/home/relayup/dev/vpn_config.cfg

    elif [[ $(grep -cw "10_Set=on" /home/relayup/dev/00_saved.cfg) -eq 1 && "$CURRENT_VERSION" -ge "200" ]];then
        cp /home/relayup/dev/vpn_config.cfg /home/update/home/relayup/dev/vpn_config.cfg
    fi

    if [ $? -ne 0 ]; then
        echo -e "Something went wrong..." > /mnt/usb/fail.log
        exit 1
    fi

    ## Cleanup
    rm -v /home/update/home/relayup/dev/html-normal/default.cfg
    rm -v /home/update/home/relayup/dev/html-normal/temp_*
    rm -v /home/update/home/relayup/dev/html-normal/00_dothis.txt

    ## Remove anon dev package if exists
    if [[ $(dpkg-query -l anon | grep "^ii " | grep -c "dev") -eq 1 ]];then
        apt-get purge anon -y
    fi

    ## Disable auto-start for anon
    if [[ $(systemctl is-enabled anon | grep -wc "enabled" ) -eq 1 ]];then
        systemctl disable anon
    fi

    ## Kill anon process if active
    if [[ $(systemctl is-active anon | grep -wc "active" ) -eq 1 ]];then
        kill $(pgrep [a]non)
    fi

    ## Modify onboot
    sed -i 's/\/home\/relayup\/dev\/Shield -R/bash \/home\/update\/dependencies.sh/g' /etc/cron.d/onboot

    ## Log
    echo "# $TIMESTAMP This Relay with Serial ID: $SHIELD_SERIAL was updated from $CURRENT_VERSION to $UPDATE_VERSION" | tee -a /mnt/usb/update_"$CURRENT_VERSION"_to_"$UPDATE_VERSION".log

    ## Shutdown Shield or trigger reboot via Shield
    if [[ "$CURRENT_VERSION" -lt "200" ]];then
        rm -v /home/relayup/dev/00_running
        kill $(pgrep Shield)
        sudo reboot
    else
        grep "01_user_password=" /mnt/usb/default.cfg > /mnt/usb/default_ext.cfg
        echo "95_SHELL=sudo reboot" >> /mnt/usb/default_ext.cfg
    fi

else
    echo "# $TIMESTAMP - This Relay with Serial ID: $SHIELD_SERIAL is on version $UPDATE_VERSION. Doing nothing!" > /mnt/usb/ALREADY_ON_LATEST_v"$UPDATE_VERSION".log
fi