#!/bin/bash

. ./function.sh
led='/usr/sbin/iTalk/led';

upload_path=$1
$led -l2 -o0 ;$led -l2 -o0; $led -l3 -o0;
Beep 1 1 0;
blink &
BLINK_PID=$!;
#2024/01/11
mkdir /tmp/Project/;
cp -rf /app/Web/public/File /tmp/Project/;
rm /tmp/Project/File/Version.txt;
rm /tmp/Project/File/Factory/Version.txt;
cp -rf /app/Web/cgi-bin /tmp/Project/;
cp -rf /app/Certificates /tmp/Project/;
cp -rf /app/DDNS/inadyn.conf /tmp/Project;
cp -rf /app/MQTT/Broker/mosquitto.conf /tmp/Project/;
cp -rf /app/runtime/project /tmp/Project/;
cp -rf /app/Wireless/wvdial.conf /tmp/Project/;
cp -rf /app/Firewall/blocklist/rule_config.json /tmp/Project/;
cp -rf /app/SNMP/File/snmpd.conf /tmp/Project/;
cp -rf /app/SNMP/File/Transform.json /tmp/Project/;


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

    expr 1;
}


Return=$(CheckTarFileName);
if [ $Return -eq -1 ]; then
    ShowCheckTarFileNameError;
    Beep 4 0.25 0.1;
    kill $BLINK_PID;
    $led -l2 -o1 ;
    exit 0;
fi

#ClearEeprom;
ShowStartInstall;
#Beep 1 1 0;
ClearApp;
CreateEnvironment;
cp -rf $upload_path/app.tar.gz /.;
sync;sync;sync;
rm -rf /factory/*;
cp -rf $upload_path/ua-arm64*.tar /factory;
sync;sync;sync;


#RemoveFactory;
#DecompressedFile;

tar --warning=no-timestamp -zxf /app.tar.gz -C /.;
sync;sync;sync;


#CopyCommonFile;
chmod 644 $upload_path/Environment/Service/*.service;
cp -rf $upload_path/Environment/Service/*.service /lib/systemd/system/;
cp -rf $upload_path/Environment/function.sh /icpdas/init/;
chmod 755 /icpdas/init/function.sh >& /dev/null;
Install_openvpn_if_needed;

#SetEnvironment;

systemctl enable ua-searchIP.service;
systemctl enable ua-rotarySwitch.service;
systemctl enable ua-web.service;
systemctl enable ua-iftttConditionTrigger.service;
systemctl enable ua-daemon.service;
systemctl enable ua-backstageService.service;
systemctl enable ua-dynamic-blocklist.service;
ChmodFile;

UpdateService $upload_path;

#DeleteResidualFile;
rm -rf $upload_path;
rm -rf /app.tar.gz;
MigrateRestartUnit;
sync;sync;sync;
SetEeprom "Successful update from utility";

#2024/01/11
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/inadyn.conf /app/DDNS;
cp -rf /tmp/Project/mosquitto.conf /app/MQTT/Broker/;
cp -rf /tmp/Project/project /app/runtime/;
cp -rf /tmp/Project/wvdial.conf /app/Wireless/;
cp -rf /tmp/Project/rule_config.json /app/Firewall/blocklist/;  
cp -rf /tmp/Project/snmpd.conf /app/SNMP/File/;
cp -rf /tmp/Project/Transform.json /app/SNMP/File/;
rm -rf /tmp/Project/;

sync;sync;sync;
#2021/01/03
kill $BLINK_PID;
$led -l2 -o1 ;
ShowInstallSuccess;
Beep  2 1 0.5;
$led -l2 -o0 ;
