#!/bin/bash
# Activate wifi if blocked
# rfkill unblock wifi
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$DIR" || exit
CMD=$1
P1=$2
P2=$3
P3=$4
P4=$5

ETH_CON="Wired connection 1"
. ../etc/server.conf
if [ -f "/boot/firmware/repetier-network.conf" ]; then
    . /boot/firmware/repetier-network.conf
fi

export LC_ALL=C

function delSSID {
    foo="$(awk '/'"$P1"'/ { flag=1 }; flag==0 { print $0 }; /network={/ { flag=0 }' <"$PWCONF")"
    if echo -e "$foo" | tail -1 | grep -q 'network={'; then
        foo=$(echo -e "$foo" | head -n -1)
    fi
    echo -e "$foo" >"$PWCONF"
}

function setHostname {
    local newName=$1
    local oldName
    oldName=$(hostname)
    foo=$(awk '!/127.0.0.1[ \t]+'"$oldName"'[ \t]*#?/' </etc/hosts)
    echo -e "$foo" >/etc/hosts
    echo -e "127.0.0.1 $newName # SERVERNAME" >>/etc/hosts
    echo -e "$newName" >/etc/hostname
    hostname "$newName"
    service avahi-daemon restart
}
# Detect in which mode wlan is working
# Returns:
# Master = works as access point
# Managed = normal wlan access
# Unconnected = no wlan connected yet
# NoWLAN = no wlan device present

function getWlanMode {
    activeSSID=""
    hasWlan=$(iwconfig 2>&1 | grep "$WLAN")
    activeSSID='Not Connected'
    if [ "$hasWlan" == "" ]; then
        wlanMode="NoWLAN"
    else
        foo=$(iwconfig "$WLAN")
        wlanMode=$(echo -e "$foo" | awk '/Mode:/ {gsub("Mode:","",$1);print $1}')
        test2=$(echo -e "$foo" | awk '/Mode:/ {print $4}')
        test=$(echo -e "$foo" | awk "/$WLAN/ {print \$2}")
        if [ "$test2" == "Mode:Master" ]; then
            wlanMode="Master"
        fi
        if [ "$wlanMode" == "Managed" ]; then
            if [ "$test" == "unassociated" ] || [ "$test2" == "Not-Associated" ]; then
                wlanMode="Unconnected"
            else
                activeSSID=$(echo -e "$foo" | awk '/ESSID/ {gsub(/ESSID:"/,"",$4);gsub(/"$/,"",$4);print $4}')
            fi
        fi
    fi
}

function prepareConnect {
    getWlanMode
    if [ "$wlanMode" == "Master" ]; then
        ./activateWLAN &>/dev/null
        sleep 5
    fi
}

function writeServerConf {
    if [ -z ${ACCESS_POINT_SECURITY+1} ]; then
        ACCESS_POINT_SECURITY=2
    fi
    cp ../etc/server.conf ../etc/server.conf.bak
    {
        echo "SSID=$SSID"
        echo "PASSWORD=$PASSWORD"
        echo "CHANNEL=$CHANNEL"
        echo "WLAN=$WLAN"
        echo "WLAN_HOTSPOT=$WLAN_HOTSPOT"
        echo "COUNTRY=$COUNTRY"
        echo "ETH_CON=\"$ETH_CON\""
    } >../etc/server.conf
    {
        echo "# ---- Start Access Point Settings ----"
        echo "# Security level for access point"
        echo "# 0 = no security"
        echo "# 1 = WPAPSK"
        echo "# 2 = WPA2 + WPAPSK"
        echo "ACCESS_POINT_SECURITY=$ACCESS_POINT_SECURITY"
        echo "# SSID of access point"
        echo "SSID=$SSID"
        echo "# Password for access point"
        echo "PASSWORD=$PASSWORD"
        echo "# Channel 1-13 on which the access point operates"
        echo "CHANNEL=$CHANNEL"
        echo "# ---- End Access Point Settings ----"
        # Change country to valid ISO-3166 code if needed to make wifi use correct channels
        echo "COUNTRY=$COUNTRY"
    } >/boot/firmware/repetier-network.conf
}

case $CMD in
getCountry)
    echo "$COUNTRY"
    ;;
setCountry)
    iw reg set "$P1"
    COUNTRY=$P1
    writeServerConf
    ;;
setAPSSID)
    SSID=$P1
    writeServerConf
    getWlanMode
    if [ "$wlanMode" == "Master" ]; then
        ./activateAP
    fi
    ;;
setAPPassword)
    PASSWORD=$P1
    writeServerConf
    getWlanMode
    if [ "$wlanMode" == "Master" ]; then
        ./activateAP
    fi
    ;;
setAPChannel)
    CHANNEL=$P1
    writeServerConf
    getWlanMode
    if [ "$wlanMode" == "Master" ]; then
        ./activateAP
    fi
    ;;
info)
    hostname=$(hostname)
    echo "hostname:$hostname"
    getWlanMode
    echo "mode:$wlanMode"
    echo "SSID:$activeSSID"
    echo "country:$COUNTRY"
    echo "AP_SSID:$SSID"
    echo "AP_Channel:$CHANNEL"
    echo "TimeZone:$(timedatectl | grep "Time zone" | cut -d ':' -f2)"
    echo "version:10"
    if [ -f "/boot/firmware/ManualWifi.conf" ]; then
        echo "manualWifi:1"
        echo "supportAP:0"
    else
        echo "manualWifi:0"
        if iw list | grep -E " AP$" &>/dev/null; then
            echo "supportAP:1"
        else
            echo "supportAP:0"
        fi
    fi
    echo "screensaver:1"
    echo "method:network_manager"
    ;;
screensaver)
    export DISPLAY=:0
    if [[ "$P1" == "0" ]]; then
        xset s off
        xset -dpms
        xset s noblank
        xset s reset
        echo "Screensaver disabled"
    else
        xset s on
        xset +dpms
        xset s blank
        xset s "$P2"
        echo "Screensaver enabled"
    fi
    ;;
setHostname)
    setHostname "$P1"
    ;;
connectPW)
    prepareConnect
    nmcli dev disconnect "$WLAN" &>/dev/null
    nmcli connection delete "$P1" &>/dev/null
    if [[ "$P3" == "" ]]; then
        P3="no"
    fi
    nmcli dev wifi connect "$P1" password "$P2" hidden "$P3" &>/dev/null
    ret=$?
    if [ $ret == 0 ]; then
        echo "OK"
    else
        nmcli connection delete "$P1" &>/dev/null
        echo "Failed"
    fi
    ;;
scan)
    activeSsid=$(iwgetid "$WLAN" -r)
    ./wlanscanner "$WLAN" "$activeSsid" "$P1"
    ;;
listConnections)
    nmcli connection show | grep -E "wireless| wifi "
    ;;
connectionDetails)
    nmcli con show "$P1"
    ;;
activateManualControl)
    cp /boot/firmware/ManualWifi.conf /etc/NetworkManager/system-connections/manual.nmconnection
    chmod 700 /etc/NetworkManager/system-connections/manual.nmconnection
    chown root /etc/NetworkManager/system-connections/manual.nmconnection
    service NetworkManager restart
    sleep 10
    nmcli --terse connection show | cut -d : -f 1 |
        while read name; do
            if [[ "$name" != "manual" ]] && [[ "$name" != "$ETH_CON" ]] && [[ "$name" != "lo" ]]; then
                nmcli connection delete "$name"
            fi
        done
    nmcli connection up manual
    ;;
connect)
    prepareConnect
    nmcli connection up "$P1" &>/dev/null
    ret=$?
    if [ $ret == 0 ]; then
        echo "OK"
    else
        ## 10 = Connection or device does not exist, so delete it
        if [ $ret == 10 ]; then
            nmcli connection delete "$P1" ifname "$WLAN" &>/dev/null
        fi
        echo "Failed"
    fi
    ;;
deleteConnection)
    nmcli connection delete "$P1" &>/dev/null
    ;;
modifySetting)
    nmcli connection mod "$P1" "$P2" "$P3" &>/dev/null
    ret=$?
    if [ $ret == 0 ]; then
        echo "OK"
    else
        nmcli connection delete "$P1" &>/dev/null
        echo "Failed"
    fi
    ;;
createConnection)
    nmcli con delete "$P1" &>/dev/null
    nmcli con add type wifi ifname "$WLAN" con-name "$P1" ssid "$P1" &>/dev/null
    ret=$?
    if [ $ret == 0 ]; then
        echo "OK"
    else
        nmcli connection delete "$P1" &>/dev/null
        echo "Failed"
    fi
    ;;
updatePassword)
    nmcli con mod "$P1" "$P2" "$P3" 802-11-wireless-security.key-mgmt "$P4" &>/dev/null
    ret=$?
    if [ $ret == 0 ]; then
        echo "OK"
    else
        if [ $ret == 0 ]; then
            nmcli connection delete "$P1" &>/dev/null
        fi
        echo "Failed"
    fi
    ;;
mode)
    getWlanMode
    echo $wlanMode
    ;;
ap)
    ./activateAP
    ;;
disableAp)
    prepareConnect
    ;;
regions)
    echo "00	Not Set"
    tail -n +26 /usr/share/zoneinfo/iso3166.tab
    ;;
channels)
    hasWlan=$(ifconfig | grep "$WLAN")
    if [ "$hasWlan" != "" ]; then
        a=$(iwlist "$WLAN" freq)
        b=$(echo "$a" | sed -e 's/Channel /\n/g' | awk '/^[0-9]+ / {print $1}')
        echo "$b"
    fi
    ;;
timezones)
    timedatectl list-timezones
    ;;
getTimezone)
    timedatectl | grep "Time zone" | cut -d ':' -f2
    ;;
setTimezone)
    timedatectl set-timezone "$P1" &>/dev/null
    echo "OK"
    ;;
ethStatus)
    a=$(nmcli connection show "$ETH_CON")
    echo "ipv4_method:$(echo "$a" | grep "ipv4.method" | cut -d ':' -f2 | awk '{$1=$1};1')"
    echo "ipv4_addresses:$(echo "$a" | grep "ipv4.addresses" | cut -d ':' -f2 | awk '{$1=$1};1' | sed -e 's/--//')"
    echo "ipv4_gateway:$(echo "$a" | grep "ipv4.gateway" | cut -d ':' -f2 | awk '{$1=$1};1' | sed -e 's/--//')"
    echo "ipv4_dns:$(echo "$a" | grep "ipv4.dns:" | cut -d ':' -f2 | awk '{$1=$1};1' | sed -e 's/--//')"
    echo "ipv6_method:$(echo "$a" | grep "ipv6.method" | cut -d ':' -f2 | awk '{$1=$1};1')"
    echo "ipv6_addresses:$(echo "$a" | grep "ipv6.addresses" | cut -d ':' -f2 | awk '{$1=$1};1' | sed -e 's/--//')"
    echo "ipv6_gateway:$(echo "$a" | grep "ipv6.gateway" | cut -d ':' -f2 | awk '{$1=$1};1' | sed -e 's/--//')"
    echo "ipv6_dns:$(echo "$a" | grep "ipv6.dns:" | cut -d ':' -f2 | awk '{$1=$1};1' | sed -e 's/--//')"
    ;;
ethUpdate)
    nmcli con down "$ETH_CON"
    nmcli con up "$ETH_CON"
    ;;
ethIP4Auto)
    nmcli con mod "$ETH_CON" ipv4.method auto ipv4.addresses "$P1" ipv4.gateway "$P2" ipv4.dns "$P3"
    ;;
ethIP6Auto)
    nmcli con mod "$ETH_CON" ipv6.method auto ipv6.addresses "$P1" ipv6.gateway "$P2" ipv6.dns "$P3"
    ;;
ethIP4Manual)
    nmcli con mod "$ETH_CON" ipv4.method manual ipv4.addresses "$P1" ipv4.gateway "$P2" ipv4.dns "$P3"
    ;;
ethIP6Manual)
    nmcli con mod "$ETH_CON" ipv6.method manual ipv6.addresses "$P1" ipv6.gateway "$P2" ipv6.dns "$P3"
    ;;
*)
    echo "Unknown command $CMD"
    ;;
esac
