#!/bin/sh
###############################################################################
#                                                                             #
#                           Update gw software                                #
#                                                                             #
###############################################################################

. /usr/local/bin/telem/functions

###############################################################################
#                                                                             #
#                         Gateway6 files and folders                          #
#                                                                             #
###############################################################################

FOLDER_BIN=/usr/bin		# Executables
FOLDER_LIB=/usr/lib		# Shared libraries
FOLDER_TEMP=/tmp		# Temporary files
NET_UPD=/root/upd/

SETUP_FILE_NEW=setup.new.tar.xz
SETUP_FILE_CURRENT=setup.tar.xz
SETUP_BINARY_FILE_CURRENT=gwSetup.bin
SETUP_BINARY_FILE_NEW=gwSetup.bin.new

SDD=/mnt/sd
SDDConfig=/mnt/sd/config
CONFIG_DIR=notset
UPD_ROOT=$FOLDER_TEMP/gwupd
UPD_LOG=$FOLDER_TEMP/res.txt
ERR_LOG=$FOLDER_TEMP/err.txt

DEFAULT_SETUP_FILE=/etc/default/setup/setup.tar.xz
DEFAULT_USER_SETUP_FILE=/etc/default/user_setup/setup.tar.xz

ETC_TELEM=/usr/local/etc/telem

STATS_DIR=/var/local/telem/stats

I2C_PROBLEM_FILE=/var/local/telem/errors/i2c-bus

GWS_GROUP=gws

clear_setup_on_boot_file=/var/local/telem/clear_setup_on_boot

reload_setup_on_boot_file=/var/local/telem/reload_setup_on_boot

reset_hw_config_script=/usr/local/bin/telem/detect-com-ports.sh

###############################################################################
#                                                                             #
#                             Script functions                                #
#                                                                             #
###############################################################################


LocateUpdateDirectory()
{
    # update from SD?
    CONFIG_DIR=$SDD
    if [ -e $CONFIG_DIR/$SETUP_FILE_NEW ]; then
        return 0
    fi

    # look inside /root folder
    CONFIG_DIR=/root
    if [ -e $CONFIG_DIR/$SETUP_FILE_NEW ]; then
        return 0
    fi

    # look inside /home/*user* folders
    for dir_name in /home/*; do
      if [ -d $dir_name ]; then
          CONFIG_DIR=$dir_name
          if [ -e $CONFIG_DIR/$SETUP_FILE_NEW ]; then
              return 0
          fi
      fi
    done

    CONFIG_DIR=$ETC_TELEM
    if [ -e $CONFIG_DIR/$SETUP_FILE_NEW ]; then
        return 0
    fi

    # Configuration from SD card
    if [ -f "$SDDConfig/$SETUP_FILE_CURRENT" ]; then
        diff -q "$SDDConfig/$SETUP_FILE_CURRENT" "$ETC_TELEM/$SETUP_FILE_CURRENT"
        if [ $? != 0 ]; then
            logg "Config on SD card is different from current, reconfiguring"
            cp "$SDDConfig/$SETUP_FILE_CURRENT" "$ETC_TELEM/$SETUP_FILE_NEW"
            CONFIG_DIR=$ETC_TELEM
            return 0
        fi
    fi

    CONFIG_DIR=notset

    return 1
}



updatePermissions()
{
    chmod +x /usr/local/bin/telem/check_permissions $1
    /usr/local/bin/telem/check_permissions $1
}

start() {
    logg "Starting telem-config extractor"

    current_setup_file=$ETC_TELEM/$SETUP_FILE_CURRENT

    # move setup files to default setup directory
    if [ -e /home/martem/$SETUP_FILE_CURRENT ]; then
        mv /home/martem/$SETUP_FILE_CURRENT* $ETC_TELEM/
        chown -R :$GWS_GROUP $ETC_TELEM
    fi


    # mount SD card if connected
    if [ -e /dev/mmcblk0p1 ]; then
        mount /dev/mmcblk0p1 /mnt/sd
    fi

    # if setup doesn't exist, clear setup
    if [ ! -e $current_setup_file ] && [ ! -e $ETC_TELEM/$SETUP_FILE_NEW ] && [ ! -e $ETC_TELEM/$SETUP_BINARY_FILE_CURRENT ] && [ ! -e $ETC_TELEM/$SETUP_BINARY_FILE_NEW ]; then
        logg "Current setup file not found"
        do_clear_setup=1
    fi

    test -e $clear_setup_on_boot_file && {
        test -e $I2C_PROBLEM_FILE && {
            rm $clear_setup_on_boot_file
        } || {
            logg "Found 'clear_setup_on_boot_file'"
            do_clear_setup=1
        }
    }
    test ! -e /etc/shadow && {
        logg "/etc/shadow not found"
        do_clear_setup=1
    }
    
    test $do_clear_setup && {
        
        test -e $STATS_DIR/device-is-booted && {
            logg "Rebooting before clearing setup"
            touch $STATS_DIR/reboot-before-setup
            reboot
            exit 0
        }
    
        logg "Starting clear setup procedure"

        rm -f $current_setup_file

        if [ -f $DEFAULT_USER_SETUP_FILE ]; then
            user_setup_file=$DEFAULT_USER_SETUP_FILE
            local _which="user"
        elif [ -f $DEFAULT_SETUP_FILE  ]; then
            user_setup_file=$DEFAULT_SETUP_FILE
            local _which="system"
        fi

        logg "Using $_which's default setup."

        cp $user_setup_file $ETC_TELEM/$SETUP_FILE_NEW
        default_setup_dir=`dirname $user_setup_file`

        rm $clear_setup_on_boot_file
    }
    
    
    test $reset_hw_config && {
        test -f $reset_hw_config_script && $reset_hw_config_script
    }
    
    if [[ -e ${reload_setup_on_boot_file} ]]; then
        cp /usr/local/etc/telem/setup.tar.xz /home/martem/setup.new.tar.xz
    fi

    # locate folder with new setup
    LocateUpdateDirectory
    if [ "$?" = "0" ]; then
        if [ "$CONFIG_DIR" != "notset" ]; then

            new_setup_file=$CONFIG_DIR/$SETUP_FILE_NEW

            diff -q $new_setup_file $current_setup_file
            if [[ $? != 0 || -e ${reload_setup_on_boot_file} ]]; then
                # different
                
                test -e $STATS_DIR/device-is-booted && {
                    logg "Rebooting before taking new setup"
                    reboot
                    exit 0
                }
                
                logg "New setup found: $new_setup_file"
                
                test -e /usr/local/bin/telem/parse_ordercode.sh && /usr/local/bin/telem/parse_ordercode.sh

                local TMP_SETUP=/tmp/setup
                ! rm -r $TMP_SETUP

                mkdir -p $TMP_SETUP || exit 1

                # On extraction failure delete bad new setup file or it will keep rebooting
                xzcat -t $new_setup_file || {
                    logg "Bad xz file, removing file: $new_setup_file"
                    ! rm $new_setup_file
                    exit 1
                }
                xzcat $new_setup_file | /usr/bin/tar x -C $TMP_SETUP || {
                    logg "Bad tar.xz file, removing file: $new_setup_file"
                    ! rm $new_setup_file
                    ! rm -r $TMP_SETUP
                    exit 1
                }

                sha512sum $new_setup_file | awk '{ print $1}' > /usr/local/etc/telem/setup.sha512
                
                # /usr directory permissions
                chown -R root:root $TMP_SETUP/*
                chmod a-rw,u+rw -R $TMP_SETUP/*

                updatePermissions $TMP_SETUP

                ! rm /usr/local/etc/telem/config.xml

                echo "nameserver 127.0.0.1" > /etc/resolv.conf

                # Remove old stuff that might not be sent from gws.exe
                ! rm /etc/openvpn/client*.conf
                ! rm -r /etc/openvpn/tun*
                ! rm /etc/ppp/peers/sim1*
                ! rm /etc/ppp/peers/sim2*
                ! rm /etc/ppp/peers/VMX53/*
                ! rm -r /etc/ssl/certs/*_web_server_cert.pem
                ! rm -r /etc/ssl/private/*_web_server_key.pem
                ! rm -r /var/www-*
                ! rm /usr/local/etc/telem/gwSetup.bin
                ! rm /etc/ppp/chap-secrets
                ! rm /etc/ppp/pap-secrets
                ! rm -r /etc/l2tp
                ! rm /etc/ppp/l2tp-ip-up
                ! rm /etc/ppp/l2tp-ip-down
                ! rm /etc/ipsec-tool.conf
                ! rm /etc/racoon/psk.txt
                ! rm /etc/racoon/racoon.conf
                ! rm /etc/racoon/ipsec-ip-up
                ! rm /etc/racoon/ipsec-ip-down
                ! rm /etc/gwpinger.conf              
                ! rm /etc/ppp/serial*.conf
                ! rm /etc/default/comtraded
                ! rm /etc/comtrade.conf
                ! rm /etc/comtradessh.conf
                ! rm /etc/comtrade_id
                ! rm /etc/watchdog.conf
                
                ! rm /etc/terminals/*
                
                ! rm /var/local/telem/gps_is_enabled
                
                ! rm -f /usr/local/etc/telem/hw-run.xml 2> /dev/null
                
                # GW6
                ! rm -f /etc/network/interfaces
                ! rm -f /etc/init.d/S40network-interfaces
                
                # GW6e & GWM
                ! rm -f /etc/init.d/network_eth1
                ! rm -f /etc/init.d/network_eth2
                ! rm -f /etc/init.d/network_eth3
                ! rm -f /etc/init.d/network_eth4
                ! rm -f /etc/init.d/network_eth5
                
                # pinger
                ! rm -rf /etc/pinger/
                
                ! rm -f /etc/crontab
                
                cp -v /etc/default/setup/log-conf.xml /usr/local/etc/telem/log-conf.xml
                
                grep '<log4j:configuration' $TMP_SETUP/usr/local/etc/telem/log-conf.xml >/dev/null || ! rm $TMP_SETUP/usr/local/etc/telem/log-conf.xml
                
                cp -r $TMP_SETUP/etc /

                cp -r $TMP_SETUP/var /

                cp -r $TMP_SETUP/usr/local /usr/

                local ssh_auth="/home/martem/.ssh/authorized_keys"
                if [ -e "$TMP_SETUP$ssh_auth" ]; then
                    mkdir -p /home/martem/.ssh
                    cp "$TMP_SETUP$ssh_auth" "$ssh_auth"
                    chown martem:martem "$ssh_auth"
                    chmod 600 "$ssh_auth"
                fi

                if [[ ! -e ${reload_setup_on_boot_file} ]]; then
                    # rename previous setup files
                    fileRotate "$current_setup_file" 3

                    mv $new_setup_file $current_setup_file

                    # Update configurations on SD card
                    if [ -d "$SDDConfig" ]; then
                        currentSDConf="$SDDConfig/$SETUP_FILE_CURRENT"
                        diff -q "$currentSDConf" "$current_setup_file"
                        if [ $? != 0 ]; then
                           fileRotate "$currentSDConf" 8
                           cp "$current_setup_file" "$currentSDConf"
                        fi
                    fi
                else
                    rm ${new_setup_file}
                    rm -f ${reload_setup_on_boot_file}
                fi
   

                test $default_setup_dir && {
                    cp -f $default_setup_dir/passwd 	/etc/
                    cp -f $default_setup_dir/shadow 	/etc/
                    cp -f $default_setup_dir/profile 	/etc/
                    cp -f $default_setup_dir/group 	/etc/
                } 
                
                updatePermissions /

                sync

                Reboot
            else
                # same, remove new file
                logg "new setup file is same as the on currently used. Remove and ignore."
                ! rm $new_setup_file
            fi
        fi
    fi
}



###############################################################################
#                                                                             #
#                                The Script                                   #
#                                                                             #
###############################################################################


stop() {
    return 0
}
restart() {
    return 0
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  old)
    num=$2
    old_file=$ETC_TELEM/$SETUP_FILE_CURRENT.$num
    
    test -e $old_file && logg "Old '`basename $ETC_TELEM/$SETUP_FILE_CURRENT.$num`' setup exists..."
    
    cp -vf $old_file $ETC_TELEM/$SETUP_FILE_NEW
    start
    ;;
  list-old)
    echo "Existing previous setups:"
    ls -1 $ETC_TELEM/$SETUP_FILE_CURRENT.*
    ;;
  restart|reload)
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit $?
