#! /bin/bash

DeleteServiceEnvironment()
{
    rm -rf /lib/systemd/system/OPC-5231*;
    rm -rf /lib/systemd/system/UA-5*;
    rm -rf /lib/systemd/system/ua-snmpd.service;
    
}

KeepProjectFile()
{
	mkdir /tmp/Project/;
	cp -rf /app/Web/public/File /tmp/Project/;
	rm -rf /tmp/Project/File/Version.txt;
    rm -rf /tmp/Project/File/Factory

	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/

	rm -rf /app/Web/public/File/TCP_Module/TcpIcpdasModule.json;
	rm -rf /app/Web/public/File/RTU_Module/RtuIcpdasModule.json;
}

RestoreProjectFiles()
{
	#2021/01/03
	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;
	# 2021/01/03
}

WebUpdateCheckTarFileName()
{
    Total=`ls -l /mnt/SD/update/*.tar  | grep "^-" | wc -l`;
    if [ "$Total" != "1" ]; then
        expr -1;
        return;
    fi
    
    Path="/mnt/SD/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;
	Sync;
}

WriteStringToWebLog()
{
	echo "$1" > /tmp/WebUpdate.log;
}

WebUpdateDecompressedFile()
{
    
	tar --warning=no-timestamp -xf /mnt/SD/update/UA-*.tar -C /.;
	if [ $? -ne 0 ]; then
		WriteStringToWebLog "Step2: Decompressed Firmware Fail.";
		rm -rf /command*.sh;
        rm -rf /function.sh;
        rm -rf /Environment;
        rm -rf /app.tar.gz ;
		mv /app_old /app;
		rm -rf /mnt/SD/update;
		mv /mnt/SD/factory_old /factory;
		Beep 4 0.001 0.5;
		exit 0;
	fi

	tar --warning=no-timestamp -zxf /app.tar.gz -C /.;
	if [ $? -ne 0 ]; then
		WriteStringToWebLog "Step2: Decompressed Firmware Fail.";
		rm -rf /app;
		rm -rf /command*.sh /function.sh /Environment /app.tar.gz;
		mv /app_old /app;
		mv /mnt/SD/factory_old /factory;
		rm -rf /mnt/SD/update;
		Sync;
		systemctl start OPC-5231-Runtime.service OPC-5231-Broker.service BackstageService.service ua-snmpd.service;
		Beep 4 0.001 0.5;
		exit 0;
	fi
    Sync;
	
}

WebUpdateDeleteDecompressedFile()
{
    rm -rf /app.tar.gz;
    rm -rf /app/VPNClient;
}

DeleteWebRedundantFile()
{
    rm -rf /mnt/SD/update/command*.sh;
    rm -rf /mnt/SD/update/function.sh;
    rm -rf /mnt/SD/update/RotarySwitch.sh;
    rm -rf /mnt/SD/update/Environment;
    rm -rf /mnt/SD/update/app.tar.gz ;
    rm -rf /mnt/SD/update/UA-*.tar;


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

DeleteOldAPPFolder()
{
	rm -rf /app_old;
	Sync;
}

RenameFactoryFolder()
{
	rm -rf /mnt/SD/factory_old;
	mv /factory /mnt/SD/factory_old;
}

CreatFactoryEnvironment()
{
	mkdir /factory;
	cp /mnt/SD/update/UA-*.tar /factory/.;
	if [ $? -ne 0 ]; then
	{
	  rm -rf /factory;
	  mv /mnt/SD/factory_old /factory;
	  WriteStringToWebLog "Step3: Update Factory Firmware Fail.";
	  Beep 4 0.001 0.5;
	}
	else
	WriteStringToWebLog "Step3: Update Factory Firmware Successful.";
	fi
	
}

DeleteOldFactoryFolder()
{
	rm -rf /mnt/SD/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 "MainProgram.sh" >& /dev/null;
    killall "MainProgram" >& /dev/null;
    killall "mosquitto" >& /dev/null;
    killall "inadyn" >& /dev/null;
    killall "BackstageService" >& /dev/null;
    systemctl stop OPC-5231-Runtime.service;
    systemctl stop OPC-5231-Broker.service;
    systemctl stop BackstageService.service;
    systemctl stop ua-snmpd.service;

}

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;
}
UsbCheckTarFileName()
{
    Total=`ls -l /mnt/USB/*.tar  | grep "^-" | wc -l`;
    if [ "$Total" != "1" ]; then
        expr -1;
        return;
    fi
    
    Path="/mnt/USB/";
    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;
}


CheckTarFileName()
{
    Total=`ls -l /mnt/SD/*.tar  | grep "^-" | wc -l`;
    if [ "$Total" != "1" ]; then
        expr -1;
        return;
    fi
    
    Path="/mnt/SD/";
    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;
}

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

CopyInstallFileToEnvironment()
{
    cp -rf /mnt/SD/UA-*.tar /.;
    Sync;
    rm -rf /factory/*;
    cp -rf /mnt/SD/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;
}
UsbComparisonTarFile()
{
    Return=0;
    TarName1=`ls /mnt/USB/*.tar`;
    TarName2=`ls /*.tar`;
    ComparisonMessage=`diff $TarName1 $TarName2`;
    if [ "$ComparisonMessage" != "" ]; then
	Return=-1;
    fi
    expr $Return;
}


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

DecompressedFile()
{
    tar --warning=no-timestamp -xf /UA-*.tar -C /.;
    Sync;
    #tar -zxf /app/runtime.tar.gz -C /app/.;
    tar --warning=no-timestamp -zxf /app.tar.gz -C /.;
    Sync;

}

UsbCopyEnvironment()
{
#Common
    CopyCommonFile;
#Wireless
    CopyWirelessFile;
}

CopyEnvironment()
{
#Common
    CopyCommonFile;
#Wireless
    CopyWirelessFile;
}

CopyCommonFile()
{
	chmod 644 /Environment/Service/*.service;
    cp -rf /Environment/Service/*.service /lib/systemd/system/;
	cp -rf /Environment/DetectionNetWork.sh /Init/;
	cp -rf /Environment/function.sh /Init/;
   	chmod 755 /Init/function.sh >& /dev/null;
}

CopyWirelessFile()
{
    Wireless_3G=`lsusb -d 05c6:`;
    Wireless_4G=`lsusb -d 2c7c:`;
    if [ "$Wireless_3G" != "" ] || [ "$Wireless_4G" != "" ]; then
        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()
{
    if [ ! -e /lib/arm-linux-gnueabihf/libudev.so.0 ]; then
     ln -s /lib/arm-linux-gnueabihf/libudev.so.1.6.4 /lib/arm-linux-gnueabihf/libudev.so.0
    fi
    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 enable dynamic-blocklist.service;
    systemctl enable DetectionNetWork.service;
}
SetEnvironment()
{
    if [ ! -e /lib/arm-linux-gnueabihf/libudev.so.0 ]; then
     ln -s /lib/arm-linux-gnueabihf/libudev.so.1.6.4 /lib/arm-linux-gnueabihf/libudev.so.0
    fi
    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 enable dynamic-blocklist.service;
    systemctl enable DetectionNetWork.service;
    systemctl disable OPC-5231-DDNS.service;
    systemctl disable UA-5000-systemlog.service;
    systemctl disable ua-snmpd.service;
#password
passwd << EOF 
icpdas
icpdas
EOF
}

SetStaticIP()
{
    Return=0;
    _IP=`ipv4set eth0 static 192.168.255.1 255.255.0.0 192.168.1.1 | grep "ipv4set"`;
    if [ "$_IP" != "ipv4set static eth0 ... 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;

#SystemLog
    chmod 777 /app/SystemLog/* >& /dev/null;

}

UsbDeleteResidualFile()
{
    rm -rf /mnt/USB/command*.sh;
    rm -rf /mnt/USB/function.sh;
    rm -rf /mnt/USB/RotarySwitch.sh;
    rm -rf /mnt/USB/Environment;
    #rm -rf /mnt/USB/app;
    rm -rf /mnt/USB/app.tar.gz;


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

    rm -rf /app/VPNClient;
}

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

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

    
}


DeleteFactoryResidualFile()
{
    
    rm -rf /UA-*.tar;
    rm -rf /command*.sh;
    rm -rf /function.sh;
    rm -rf /Environment;
    rm -rf /app.tar.gz;
    rm -rf /app/VPNClient;
}

Sync()
{
    sync;sync;sync;
}

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

SetEeprom() 
{
   
    if [[ -z "$1" ]]; then
        return 1
    fi
    local Message
    Message=$(date +%Y/%m/%d-%H:%M:%S)" $1";
    ClearEeprom
    /app/Eeprom/eeprom_init || return 1
    /app/Eeprom/eeprom_write "$Message" || return 1
    /app/Eeprom/eeprom_fini || return 1
}


Install_openvpn_if_needed() 
{
    # Check if OpenVPN is installed using dpkg
    if dpkg -l | grep -q openvpn
    then
        echo "OpenVPN is already installed."
    else
        echo "OpenVPN is not installed. Installing now..."

        # Define the package path
        PACKAGE_PATH="/app/VPNClient"

        # Define the packages to install in the correct order
        PACKAGES=(
            "liblzo2-2_2.08-1.2_armhf.deb"               # Install lzo library first
            "libpkcs11-helper1_1.11-5_armhf.deb"         # Install pkcs11-helper next
            "openvpn_2.3.10-1ubuntu2.2_armhf.deb"        # Install OpenVPN last
        )

        # Iterate over the packages and install them
        for PACKAGE in "${PACKAGES[@]}"
        do
            PACKAGE_FILE="$PACKAGE_PATH/$PACKAGE"
            if [ -f "$PACKAGE_FILE" ]; then
                 DEBIAN_FRONTEND=noninteractive dpkg -i "$PACKAGE_FILE"
            else
                echo "Package file $PACKAGE_FILE not found."
            fi
        done

        echo "OpenVPN and dependencies have been installed."
    fi
}

clear_openvpn_conf() 
{
    local OPENVPN_DIR="/etc/openvpn"
    #mkdir -p "$OPENVPN_DIR"
    find "$OPENVPN_DIR" -maxdepth 1 -type f -name "*.conf" -delete
    rm -rf "$OPENVPN_DIR/credentials"
}

ResetFirewall()
{
    ufw default allow incoming;
    echo "y" | ufw reset;
    echo "y" | ufw enable;
    rm -f /etc/ufw/*.rules.*
    rm -f /icpdas/whitelist/whitelist;
}

UpdateComPortSetting()
{
    # 判斷是否有擴充卡
    if lsusb | grep -q "1b5c:0007"; then
        HAS_EXPANSION=1
    else
        HAS_EXPANSION=0
    fi

    if [ "${HAS_EXPANSION}" = "1" ]; then
        # Factory 設定（有擴充卡）
        cp /app/ComPortDeviceSetting/ExpansionComPortInterfaceSetting.json \
           /app/Web/public/File/Factory/ComPortInterfaceSetting.json

        # Runtime 設定：只有在 ttyO6~9 全部不存在時才新增
        python3 <<'EOF'
import json
from collections import OrderedDict

CFG = "/app/Web/public/File/ComPortInterfaceSetting.json"
PORTS = ["ttyO6","ttyO7","ttyO8","ttyO9"]

with open(CFG) as f:
    data = json.load(f, object_pairs_hook=OrderedDict)

missing = [p for p in PORTS if p not in data]

if len(missing) == len(PORTS):
    for i,p in enumerate(PORTS):
        data[p] = {
            "DevicePath": "/dev/ttyUSB{}".format(i),
            "BaudRate": 9600,
            "DataBits": 8,
            "Parity": "None",
            "StopBits": 1,
            "PollingRate": 500
        }

with open(CFG,"w") as f:
    json.dump(data,f,indent=4)
EOF

    else
        # Factory 設定（無擴充卡）
        cp /app/ComPortDeviceSetting/ComPortInterfaceSetting.json \
           /app/Web/public/File/Factory/ComPortInterfaceSetting.json

        # Runtime 設定：移除 ttyO6~9（若存在）
        python3 <<'EOF'
import json
from collections import OrderedDict

CFG = "/app/Web/public/File/ComPortInterfaceSetting.json"
PORTS = ["ttyO6","ttyO7","ttyO8","ttyO9"]

with open(CFG) as f:
    data = json.load(f, object_pairs_hook=OrderedDict)

for p in PORTS:
    data.pop(p, None)

with open(CFG,"w") as f:
    json.dump(data,f,indent=4)
EOF
    fi
}


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;
}

# 工廠還原時呼叫：清除定時重啟服務 (ua-restart-hourly) unit，回出廠乾淨狀態。
ClearRestartUnit()
{
    SYSD=/etc/systemd/system
    systemctl stop    ua-restart-hourly.timer   >/dev/null 2>&1
    systemctl disable ua-restart-hourly.timer   >/dev/null 2>&1
    systemctl stop    ua-restart-hourly.service >/dev/null 2>&1
    rm -f "$SYSD/ua-restart-hourly.timer" "$SYSD/ua-restart-hourly.service"
    systemctl daemon-reload
    systemctl reset-failed >/dev/null 2>&1
}



