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

ETH_CON="Wired connection 1"
. ../etc/server.conf
export LC_ALL=C

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

function setHostname {
 NEWNAME=$1
 oldname=$(hostname)
 foo=$(cat "/etc/hosts" | awk '!/127.0.0.1[ \t]+'$oldname'[ \t]*#?/')
 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 {
    cp ../etc/server.conf ../etc/server.conf.bak
    echo "SSID=$SSID" > ../etc/server.conf
    echo "PASSWORD=$PASSWORD" >> ../etc/server.conf
    echo "CHANNEL=$CHANNEL" >> ../etc/server.conf
    echo "WLAN=$WLAN" >> ../etc/server.conf
    echo "WLAN_HOTSPOT=$WLAN_HOTSPOT" >> ../etc/server.conf
    echo "COUNTRY=$COUNTRY" >> ../etc/server.conf
    echo "ETH_CON=\"$ETH_CON\"" >> ../etc/server.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/wpa_supplicant-wlan0.conf" ]; then
      echo "manualWifi:1"
	    echo "supportAP:0"
    else
      echo "manualWifi:0"
  	  iw list | grep "* AP$" &>/dev/null
  	  if [ $? == 0 ]; then
    	  echo "supportAP:1"
      else
  	    echo "supportAP:0"
      fi
    fi
	  echo "screensaver:1"
	;;
  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 | egrep "wireless| wifi "
	;;
  connectionDetails)
  	nmcli con show $P1
  	;;
  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"
	cat /usr/share/zoneinfo/iso3166.tab | tail -n +26
	;;
  channels)
     haswlan=`ifconfig | grep $WLAN`
     if [ "$haswlan" != "" ] ; then
          a=$(iwlist $WLAN freq)
          #a=$(iwlist $WLAN freq & > /dev/null)
          b=$(echo $a | sed -e 's/Channel /\n/g'|awk '/^[0-9]+ / {print $1}')
          echo "$b"
     fi
 	 ;;
  timezones)
    timedatectl list-timezones
    ;;
  getTimezone)
    echo $(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')"
    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')"
    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')"
    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')"
    ;;
  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

