#! /bin/sh
DeleteServiceEnvironment()
{
    rm -rf /lib/systemd/system/OPC-5231*;
    rm -rf /lib/systemd/system/UA-5*;
}
KeepProjectFile()
{
	mkdir /tmp/Project/;
	cp -rf /app/Web/public/File /tmp/Project/;
	rm /tmp/Project/File/Version.txt;
	cp -rf /app/Web/cgi-bin /tmp/Project/;
	cp -rf /app/Certificates /tmp/Project/;
	cp -rf /app/DDNS /tmp/Project/;
	cp -rf /app/MQTT /tmp/Project/;
	cp -rf /app/runtime/project /tmp/Project/;
	rm -rf /app/Web/public/File/TCP_Module/TcpIcpdasModule.json;
	rm -rf /app/Web/public/File/RTU_Module/RtuIcpdasModule.json;
}
RestoreProjectFiles()
{
	#2020/04/20
	cp -rf /tmp/Project/File /app/Web/public/;
	cp -rf /tmp/Project/cgi-bin /app/Web/;
	cp -rf /tmp/Project/Certificates /app/;
	cp -rf /tmp/Project/DDNS /app/;
	cp -rf /tmp/Project/MQTT /app/;
	cp -rf /tmp/Project/project /app/runtime/;
	cp -rf /tmp/Project/Wireless /app/;
	rm -rf /tmp/Project/;
	Sync;
	# 2020/04/20
}

WebUpdateCheckTarFileName()
{
    Total=`ls -l /mnt/update/*.tar  | grep "^-" | wc -l`;
    if [ "$Total" != "1" ]; then
        expr -1;
        return;
    fi
    
    Path="/mnt/update/";
    TarName=`ls "$Path"ua-*.tar`;
    if [ "$TarName" = "" ]; then
        expr 0;
        return;
    fi

    mv $TarName "$Path"ICPDAS_Temp_app.tar;
    TarName1="UA-";
    TarName2=`echo $TarName | awk -F'-' '{print $2}'`;
    TarName=$TarName1$TarName2;
    mv "$Path"ICPDAS_Temp_app.tar $Path$TarName;
    expr 1;
}
RenameAPPFolder()
{
	rm -rf /app_old;
	mv /app /app_old;
}
WriteStringToWebLog()
{
	echo "$1" > /tmp/WebUpdate.log;
}
WebUpdateDecompressedFile()
{
    tar -xf /mnt/update/UA-*.tar -C /.;
    Sync;
	Return=$(WebUpdateComparisonAPPFile);
	if [ $Return -eq -1 ]; then
		WriteStringToWebLog "Step2: Decompressed Firmware Fail.";
		Beep 4 0.001 0.5;
		rm -rf /app; mv /app_old /app;
		#ShowComparisonTarFileError;
		#Beep 4 0.001 0.5;
		exit 0;
	fi
    (
		tar -zxf /app/runtime.tar.gz -C /app/. &&\
		Sync && \
		tar -zxf /app/C_CXX_LIB/unixODBC.tar.gz -C /app/C_CXX_LIB/. && \
		tar -zxf /app/C_CXX_LIB/runtime.tar.gz -C /app/C_CXX_LIB/. && \
		tar -zxf /app/C_CXX_LIB/freetds.tar.gz -C /app/C_CXX_LIB/. && \
		tar -zxf /app/C_CXX_LIB/mysql.tar.gz -C /app/C_CXX_LIB/.;
		Sync;
	) || (WriteStringToWebLog "Step2: Decompressed Firmware Fail."; Beep 4 0.001 0.5; rm -rf /app; mv /app_old /app;)
}
WebUpdateComparisonAPPFile()
{
    Return=0;
    ComparisonMessage=`diff -r /app/ /mnt/update/app/`;
    if [ "$ComparisonMessage" != "" ]; then
	Return=-1;
    fi
    expr $Return;
}
WebUpdateDeleteDecompressedFile()
{
    rm -rf /app/runtime.tar.gz;
    rm -rf /app/C_CXX_LIB/*.tar.gz;
}
DeleteWebRedundantFile()
{
    rm -rf /mnt/update/command*.sh;
    rm -rf /mnt/update/function.sh;
    rm -rf /mnt/update/RotarySwitch.sh;
    rm -rf /mnt/update/Environment;
    rm -rf /mnt/update/app;

    rm -rf /UA-*.tar;
    rm -rf /command*.sh;
    rm -rf /function.sh;
    rm -rf /Environment;
}
DeleteOldAPPFolder()
{
	rm -rf /app_old;
}
RenameFactoryFolder()
{
	rm -rf /factory_old;
	mv /factory /factory_old;
}
CreatFactoryEnvironment()
{
	mkdir /factory;
	cp /mnt/update/UA-*.tar /factory/.;
	ComparisonMessage=`diff -r /factory/UA-*.tar /mnt/update/UA-*.tar`;
    if [ "$ComparisonMessage" != "" ]; then
	{
		rm -rf /factory;
		mv /factory_old /factory;
		WriteStringToWebLog "Step1: Update Factory Firmware Fail.";
		Beep 4 0.001 0.5;
		exit 0;
	}
	fi
}
DeleteOldFactoryFolder()
{
	rm -rf /factory_old;
}












Beep()
{
  for(( i=0; i<$1; i=i+1))
  do
     cd /sys/class/pwm/ehrpwm.0:1;
     echo 100 > period_freq;
     echo 50 > duty_percent;
     echo 1 > run;
     uSecond=`awk -v x=$2 -v y=1000000 'BEGIN {printf "%d",x*y}'`;
     usleep $uSecond;
     echo 0 > run;
     uSecond=`awk -v x=$3 -v y=1000000 'BEGIN {printf "%d",x*y}'`;
     usleep $uSecond;
  done
}

ClearApp()
{
	killall "MainProgramWDT.sh" >& /dev/null;
	killall "MainProgram.sh" >& /dev/null;
    killall "MainProgram" >& /dev/null;
    killall "mosquitto" >& /dev/null;
    killall "inadyn" >& /dev/null;
    killall "BackstageService" >& /dev/null;
}

RemoveApp()
{
    rm -rf /app;
    rm -rf /lib/systemd/system/OPC-5231*;
    rm -rf /lib/systemd/system/UA-5*;
}

RemoveFactory()
{
    rm -rf /factory;
}

CreateEnvironment()
{
    mkdir /factory;
    Sync;
}

CheckTarFileName()
{
    Total=`ls -l /mnt/*.tar  | grep "^-" | wc -l`;
    if [ "$Total" != "1" ]; then
        expr -1;
        return;
    fi
    
    Path="/mnt/";
    TarName=`ls "$Path"ua-*.tar`;
    if [ "$TarName" = "" ]; then
        expr 0;
        return;
    fi

    mv $TarName "$Path"ICPDAS_Temp_app.tar;
    TarName1="UA-";
    TarName2=`echo $TarName | awk -F'-' '{print $2}'`;
    TarName=$TarName1$TarName2;
    mv "$Path"ICPDAS_Temp_app.tar $Path$TarName;
    expr 1;
}

CopyInstallFileToEnvironment()
{
    cp -rf /mnt/UA-*.tar /.;
    Sync;
    rm -rf /factory/*;
    cp -rf /mnt/UA-*.tar /factory;
    Sync;
}

CopyFactoryFileToEnvironment()
{
    cp -rf /factory/UA-*.tar /.;
    Sync;
}

ComparisonFactoryTarFile()
{
    Return=0;
    TarName1=`ls /factory/*.tar`;
    TarName2=`ls /*.tar`;
    ComparisonMessage=`diff $TarName1 $TarName2`;
    if [ "$ComparisonMessage" != "" ]; then
	Return=-1;
    fi
    expr $Return;
}

ComparisonTarFile()
{
    Return=0;
    TarName1=`ls /mnt/*.tar`;
    TarName2=`ls /*.tar`;
    ComparisonMessage=`diff $TarName1 $TarName2`;
    if [ "$ComparisonMessage" != "" ]; then
	Return=-1;
    fi
    expr $Return;
}

DecompressedFile()
{
    tar -xf /UA-*.tar -C /.;
    Sync;
    tar -zxf /app/runtime.tar.gz -C /app/.;
    Sync;

    tar -zxf /app/C_CXX_LIB/unixODBC.tar.gz -C /app/C_CXX_LIB/.;
    tar -zxf /app/C_CXX_LIB/runtime.tar.gz -C /app/C_CXX_LIB/.;
    tar -zxf /app/C_CXX_LIB/freetds.tar.gz -C /app/C_CXX_LIB/.;
    tar -zxf /app/C_CXX_LIB/mysql.tar.gz -C /app/C_CXX_LIB/.;
    Sync;
}
UsbCopyEnvironment()
{
#Common
    CopyCommonFile;
#Wireless
    CopyWirelessFile;
}
CopyEnvironment()
{
#time
    cp -rf /Environment/Service/timesyncd.conf /etc/systemd/;
    cp -rf /Environment/Service/Taipei /usr/share/zoneinfo/Asia/;
#Common
    CopyCommonFile;
#Wireless
    CopyWirelessFile;
}
CopyCommonFile()
{
	chmod 644 /Environment/Service/*.service;
    cp -rf /Environment/Service/*.service /lib/systemd/system/;
    cp -rf /Environment/Service/profile /etc/;
# log
    cp -rf /Environment/Service/root /var/spool/cron/;
    chmod 644 /var/spool/cron/root;
}

CopyWirelessFile()
{
    Wireless_3G=`lsusb -d 05c6:`;
    Wireless_4G=`lsusb -d 2c7c:`;
    if [ "$Wireless_3G" != "" ] || [ "$Wireless_4G" != "" ]; then
        cp -rf /Environment/Wireless/wvdial* /etc/ppp/peers/.;
        cp -rf /Environment/Wireless/PPP0route /etc/ppp/ip-up.d/.;
        cp -rf /Environment/Service/UA-Wireless.service  /lib/systemd/system/;
    else
        rm -rf /app/Wireless/*;
    fi
}
UsbSetEnvironment()
{
	systemctl disable ntpdate.service;
    systemctl enable OPC-5231-SearchIP.service;
    systemctl enable UA-5000-RotarySwitch.service;
    systemctl enable Nodejs.service;
    systemctl enable IftttConditionTrigger.service;
    systemctl enable Daemon.service;
    systemctl enable UA-Wireless.service;
    systemctl enable BackstageService.service;
    systemctl disable OPC-5231-NTP.service;
	systemctl disable MainProgramWDT.service;
}
SetEnvironment()
{
    timedatectl set-ntp true;
    timedatectl set-timezone 'Asia/Taipei';

    systemctl disable ntpdate.service;
    systemctl enable OPC-5231-SearchIP.service;
    systemctl enable UA-5000-RotarySwitch.service;
    systemctl enable OPC-5231-Runtime.service;
    systemctl enable OPC-5231-Broker.service;
    systemctl enable Nodejs.service;
    systemctl enable IftttConditionTrigger.service;
    systemctl enable Daemon.service;
    systemctl enable UA-Wireless.service;
    systemctl enable BackstageService.service;
    systemctl disable OPC-5231-NTP.service;
    systemctl disable OPC-5231-DDNS.service;
	systemctl disable MainProgramWDT.service;
#password
passwd << EOF 
icpdas
icpdas
EOF
}

SetStaticIP()
{
    Return=0;
    _IP=`ipv4set static 192.168.255.1 255.255.0.0 192.168.1.1`;
    if [ "$_IP" != "ipv4set static ... OK" ]; then
          Return=-1;
    fi
    expr $Return;
}

ChmodFile()
{
    chmod 777 /app/* -R;
    chmod 777 /app/MQTT/Broker/* >& /dev/null;
    chmod 777 /app/runtime/MainProgram >& /dev/null;
    chmod 777 /RotarySwitch.sh >& /dev/null;
    chmod 777 /app/SearchIP/* >& /dev/null;
    chmod 777 /app/Web/* >& /dev/null;
    chmod 777 /app/DBus/* >& /dev/null;
#Wireless
    chmod 777 /app/Wireless/* >& /dev/null;
    chmod 777 /etc/ppp/ip-up.d/PPP0route >& /dev/null;
#eeprom
    chmod 777 /app/Eeprom/* >& /dev/null;
#database
    chmod 777 /app/BackstageService/bin/* >& /dev/null;
    chmod 777 /app/DatabaseConnectionTest/bin/* >& /dev/null;
#IoTstar
    chmod 777 /app/IoTstar/bin/* >& /dev/null;
}

DeleteResidualFile()
{
    rm -rf /mnt/command*.sh;
    rm -rf /mnt/function.sh;
    rm -rf /mnt/RotarySwitch.sh;
    rm -rf /mnt/Environment;
    rm -rf /mnt/app;

    rm -rf /UA-*.tar;
    rm -rf /command*.sh;
    rm -rf /function.sh;
    rm -rf /Environment;

    rm -rf /app/runtime.tar.gz;
    rm -rf /app/C_CXX_LIB/*.tar.gz;
}

DeleteFactoryResidualFile()
{
    rm -rf /factory/command*.sh;
    rm -rf /factory/function.sh;
    rm -rf /factory/RotarySwitch.sh;
    rm -rf /factory/Environment;
    rm -rf /factory/app;
}

Sync()
{
    sync;sync;sync;
}

ClearEeprom()
{
    /app/Eeprom/eeprom_init >& /dev/null;
    /app/Eeprom/eeprom_write "" >& /dev/null;
    /app/Eeprom/eeprom_fini >& /dev/null;
}

SetEeprom()
{
    ClearEeprom;
    Message=`date +%Y/%m/%d-%H:%M:%S_$1_InstallSuccess`;
    /app/Eeprom/eeprom_init;
    /app/Eeprom/eeprom_write $Message;
    /app/Eeprom/eeprom_fini;
}

Runtimepackage_verification()
{
    Return=0;
    files=`tar -tf /app/runtime.tar.gz`;
    for path in $files
    do
        absoulte_name=/app/$path;
        if [ -d $absoulte_name ]; then
            continue
        elif [ -f $absoulte_name ]; then
            continue 
        else
            Return=-1;
            break
        fi
    done
    expr $Return;
}

ShowStartInstall()
{
    printf "\E[0;32;40m";
    echo "########## Start Install ##########";
    printf "\E[0m";
    led -l2 -g0 -r0;
    led -l2 -g1 -r0;
}

ShowNetworkConnectionError()
{
    printf "\E[0;31;40m";
    echo "xxxxxxxxxx Please check your network connection xxxxxxxxxx";
    printf "\E[0m";
    led -l2 -g0 -r0;
    led -l2 -g0 -r1;
    Sync;
}

ShowCheckTarFileNameError()
{
    printf "\E[0;31;40m";
    echo "xxxxxxxxxx Check tar file name xxxxxxxxxx";
    printf "\E[0m";
    led -l2 -g0 -r0;
    led -l2 -g0 -r1;
    Sync;
}

ShowComparisonTarFileError()
{
    printf "\E[0;31;40m";
    echo "xxxxxxxxxx Comparison file error xxxxxxxxxx";
    printf "\E[0m";
    led -l2 -g0 -r0;
    led -l2 -g0 -r1;
    Sync;
}

ShowRuntimePackageError()
{
    printf "\E[0;31;40m";
    echo "xxxxxxxxxx Runtime package file is missing xxxxxxxxxx";
    printf "\E[0m";
    led -l2 -g0 -r0;
    led -l2 -g0 -r1;
    Sync;
}

ShowInstallSuccess()
{
    printf "\E[0;32;40m";
    echo "########## Install success ##########";
    printf "\E[0m";
    led -l2 -g0 -r0;
}

ChangeComPortDeviceSetting()
{
    printf "\E[0;32;40m";
    echo "########## Install success ##########";
    printf "\E[0m";
    led -l2 -g0 -r0;
}

