#!/usr/bin/env bash
#GUI to toogle ufw on/off, by PPC, GPL license, 20/2/2023
#runit code added by anticapitalista

# localisation
TEXTDOMAINDIR=/usr/share/locale
TEXTDOMAIN=antix_firewall_toggle

#variables, for easy localization/change
app_name=$"antiX (UFW) Firewall Toggle"
text=$"Firewal status:"
on=$"Enable Firewall"
off=$"Disable Firewall"
not_root_message=$"You entered the wrong password or you cancelled"
enabled_localized=$"ON"
disabled_localized=$"OFF"

#Variables:
windowicon="/usr/share/icons/papirus-antix/48x48/apps/preferences-system-firewall.png"

### Check if user is Root, if not, pop up window asking for password, to run updater. If Cancelled, exit.
# adapted from  https://stackoverflow.com/questions/42875809/checking-sudo-in-bash-script-with-if-statements 
if [[ "$EUID" = 0 ]]; then
    result="already root"
else
    gksudo "$app_name"
    if sudo true; then
        result="already root"
    else
        result="NOT root"
        yad --window-icon=$windowicon --center --width=250 --text-align=center  --text="$not_root_message" --title="$app_name" --image="/usr/share/icons/papirus-antix/48x48/emblems/emblem-rabbitvcs-obstructed.png" --button=' x '  --borders=5 --fixed
        exit 1
    fi
fi

#Procede with the script, if with elevated privileges
#Get Firewall status
fw_status=$(sudo ufw status| cut -f 2 -d ":")
######################################### 
#Try to localize status of the Firewall:
[ "$fw_status" == " active" ] && fw_status=$enabled_localized
[ "$fw_status" == " inactive" ] && fw_status=$disabled_localized
######################################### 

yad --window-icon=$windowicon --title="$app_name" --image=$windowicon --center --text="\n $text $fw_status" --button="$on":1 --button="$off":2 --width=350

selection=$?

if [[ $selection -eq 1 ]]; then
 sudo ufw enable
 #if using runit we need to sym link the service and then start it
   if [ -f /sbin/runit ] && [ ! -h "/etc/service/ufw" ]; then
    sudo ln -s /etc/sv/ufw/ /etc/service/ && sudo sv start /etc/sv/ufw
   fi 
 fw_status=$(sudo ufw status| cut -f 2 -d ":")
fi

if [[ $selection -eq 2 ]]; then
 sudo ufw disable
 #if using runit we need to stop ufw and then remove the sym link
    if [ -f /sbin/runit ] && [ -d "/etc/service/ufw" ]; then
      sudo sv stop /etc/sv/ufw && sudo unlink /etc/service/ufw
    fi
 fw_status=$(sudo ufw status| cut -f 2 -d ":")
fi

#Display final FW status
fw_status=$(sudo ufw status| cut -f 2 -d ":")
######################################### 
#Try to localize status of the Firewall:
[ "$fw_status" == " active" ] && fw_status=$enabled_localized
[ "$fw_status" == " inactive" ] && fw_status=$disabled_localized
######################################### 
yad --window-icon=$windowicon --title="$app_name" --center --text="$text $fw_status" --button=" x " --width=350 --timeout=5  --timeout-indicator=bottom
