#!/bin/bash

QUERY_STRING=$(echo "${QUERY_STRING}" | sed 's/;//g')
function urldecode() { : "${*//+/ }"; echo -e "${_//%/\\x}"; }

if [ "${QUERY_STRING}" ]; then
    export IFS="&"
    for cmd in ${QUERY_STRING}; do
        if [[ "$cmd" == *"="* ]]; then
            key=$(echo $cmd | awk -F '=' '{print $1}')
            value=$(echo $cmd | awk -F '=' '{print $2}')
            eval $key=$(urldecode $value)
        fi
    done
fi

if [ -z "$status" ] || [ -z "$IpDNS" ] || [ -z "$cooldown" ] || [ -z "$failures" ] || [ -z "$action" ]; then
    response="Missing parameters. Please provide the following parameters: IpDNS, cooldown, failures, action."
    echo "Content-type: text/plain"
    echo ""
    echo "$response"
    exit 1
fi

if [ "$status" == "enabled" ]; then
    watch_script="/usrdata/simpleadmin/script/watchat.sh"
    mount -o remount,rw /

    cat <<EOF > $watch_script
#!/bin/bash

ip_or_dns="$IpDNS"
cooldown=$cooldown
action="$action"
fail_count=0
max_failures=$failures

# Process the action variable. 

# Create a JSON file containing the parameters of the script
echo -n '{"ip_or_dns":"$ip_or_dns","cooldown":$cooldown,"action":"$action","fail_count":$fail_count,"max_failures":$max_failures}' > /tmp/watchatParams.json


while true; do
    if ping -c 1 -W 1 \$ip_or_dns > /dev/null; then
        fail_count=0
        echo "Success at \$(date)" >> /tmp/watchat.log
        # Convert /tmp/watchat.log to json format
        echo -n '{"log":[' > /tmp/watchat.json
        cat /tmp/watchat.log | sed 's/$/,/' | tr -d '\n' | sed 's/,$//' >> /tmp/watchat.json
        echo -n ']}' >> /tmp/watchat.json
    else
        ((fail_count++))
        if [ \$fail_count -ge \$max_failures ]; then
            case "\$action" in
                reboot)
                    echo "Rebooting system..."
                    /sbin/reboot
                    ;;
                switch_sim)
                    echo "Switching SIM..."
                    echo -ne "AT+CNMI=2,1\r" > /dev/ttyOUT2
                    sleep 1
                    echo "Switching SIM at \$(date)" >> /tmp/watchat.log
                    ;;
                none)
                    echo "No action taken."
                    echo "No action taken at \$(date)" >> /tmp/watchat.log
                    ;;
                *)
                    echo "Unknown action: \$action"
                    ;;
            esac
            # Reset fail count
            fail_count=0
        fi
    fi
    echo "Fail count: \$fail_count at \$(date)" >> /tmp/watchat.log
    # Convert /tmp/watchat.log to json format
    echo -n '{"log":[' > /tmp/watchat.json
    cat /tmp/watchat.log | sed 's/$/,/' | tr -d '\n' | sed 's/,$//' >> /tmp/watchat.json
    echo -n ']}' >> /tmp/watchat.json
    sleep \$cooldown
done
EOF

    chmod +x $watch_script

    cat <<EOF > /lib/systemd/system/watchcat.service
[Unit]
Description=Ping Watcher Service

[Service]
ExecStart=$watch_script
Restart=always

[Install]
WantedBy=multi-user.target
EOF

    ln -s /lib/systemd/system/watchcat.service /etc/systemd/system/multi-user.target.wants/watchcat.service

    systemctl daemon-reload
    systemctl start watchcat.service

    response="Script created at $watch_script and made executable. Service created and started."

elif [ "$status" == "disabled" ]; then
    watch_script="/usrdata/simpleadmin/script/watchat.sh"
    rm -f $watch_script

    systemctl stop watchcat.service
    rm -f /lib/systemd/system/watchcat.service
    rm -f /etc/systemd/system/multi-user.target.wants/watchcat.service

    systemctl daemon-reload

    response="Script removed at $watch_script. Service stopped and removed."
else
    response="Invalid status. Please provide either enabled or disabled."
fi

echo "Content-type: text/plain"
echo ""
echo "$response"