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

. basicFunctions

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=$(iwgetid $WLAN -r)
      fi
    fi
  fi
}

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



function deleteWPASupplicant {
  cat > /etc/wpa_supplicant/wpa_supplicant-${WLAN}.conf <<EOF
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=$COUNTRY

EOF
  WLAN_SSID=""
  WLAN_PASSWORD_METHOD=""
  WLAN_PASSWORD=""
  WLAN_SSID_HIDDEN="false"
  WLAN_4_MODE="auto"
  WLAN_4_STATIC=""
  WLAN_4_DNS=""
  WLAN_4_GATEWAY=""
  WLAN_6_MODE="auto"
  WLAN_6_STATIC=""
  WLAN_6_DNS=""
  WLAN_6_GATEWAY=""
  writeServerConf
	wpa_cli -i $WLAN reconfigure
}

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:9"
	  iw list | grep "* AP$" &>/dev/null
	  if [ $? == 0 ]; then
  	  echo "supportAP:1"
    else
  	  echo "supportAP:0"
    fi
	  echo "screensaver:1"
	  echo "method:wpa_supplicant"
	;;
  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)
	  if [[ $P3 == "" ]] ; then
	    P3="false"
	  fi
	  WLAN_SSID_HIDDEN=$P3
	  WLAN_SSID=$P1
	  WLAN_PASSWORD=$P2
	  WLAN_PASSWORD_METHOD="wpa-psk"
	  writeServerConf
	  writeWPASupplicant
	  prepareConnect
	  #service wpa_supplicant restart
		echo "OK"
  	;;
  scan)
    activessid=$(iwgetid $WLAN -r)
    ./wlanscanner $WLAN "$activessid" "$P1"
	  ;;
  listConnections)
     getWlanMode
     # Falke               1739e535-397f-4c8e-aec2-d12f23f0d5bc  802-11-wireless  wlan0
     if [ "$WLAN_SSID" != "" ] ; then
       echo "$WLAN_SSID 1739e535-397f-4c8e-aec2-d12f23f0d5bc 802-11-wireless $WLAN"
     fi
     # Hotspot             985e7ee6-ffa0-4a7e-82f9-b848a29532d6  802-11-wireless  --
     if [ "$wlanmode" = "Master" ] ; then
       echo "Hotspot 985e7ee6-ffa0-4a7e-82f9-b848a29532d6 802-11-wireless $WLAN"
     fi
	;;
  connectionDetails)
  	# Not used any more
  	;;
  connect)
    if [ $AP_ACTIVE = "true" ] ; then
    	prepareConnect &> /dev/null
    else
  	  updateDHCPCD &> /dev/null
  	  writeWPASupplicant &> /dev/null
  	fi
  	RES="Failed"
  	for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
    do
      sleep 1
      getWlanMode
      if [ "$wlanmode" == "Managed" ] &&  [ "$P1" == "$activeSSID" ] ; then
  	    RES="OK"
  	    break
  	  fi
    done
    echo "$RES"
	  ;;
  deleteConnection)
    getWlanMode
    if [ "$P1" == "$WLAN_SSID" ] ; then
  	  deleteWPASupplicant &> /dev/null
  	fi
  	echo "OK"
  	;;
  modifySetting)
    if [ "$P1" == "$WLAN_SSID" ] ; then
      if [ "$P2" == "ipv4.method" ] ; then
        WLAN_4_MODE="$P3"
      fi
      if [ "$P2" == "ipv4.addresses" ] ; then
        # ip/mask gateway
        IFS=' ' # space is set as delimiter
        read -ra ADDR <<< "$P3"
        WLAN_4_STATIC="static ip_address=${ADDR[0]}"
        if [ "${ADDR[1]}" != "" ] ; then
          WLAN_4_GATEWAY="static routers=${ADDR[1]}"
        fi
      fi
      if [ "$P2" == "ipv4.dns" ] ; then
        WLAN_4_DNS="static domain_name_servers=$P3"
      fi
      if [ "$P2" == "ipv6.method" ] ; then
        WLAN_6_MODE="$P3"
      fi
      if [ "$P2" == "ipv6.addresses" ] ; then
        IFS=' ' # space is set as delimiter
        read -ra ADDR <<< "$P3"
        WLAN_6_STATIC="static ip6_address=${ADDR[0]}"
        if [ "${ADDR[1]}" != "" ] ; then
           if [ "$WLAN_4_GATEWAY" == "" ] ; then
              WLAN_4_GATEWAY="static routers=${ADDR[1]}"
           else
              WLAN_4_GATEWAY="$WLAN_4_GATEWAY ${ADDR[1]}"
           fi
        fi
      fi
      if [ "$P2" == "ipv6.dns" ] ; then
        if [ "$WLAN_4_DNS" == "" ] ; then
           WLAN_4_DNS="static domain_name_servers=$P3"
        else
           WLAN_4_GATEWAY="$WLAN_4_DNS $P3"
        fi
      fi
      if [ "$P2" == "802-11-wireless.hidden" ] ; then

        WLAN_SSID_HIDDEN="$P3"
      fi
      writeServerConf
    fi
		echo "OK"
    ;;
  createConnection)
    WLAN_SSID="$P1"
    WLAN_SSID_HIDDEN="false"
    WLAN_PASSWORD=""
    WLAN_PASSWORD_METHOD=""
    writeServerConf
		echo "OK"
    ;;
  updatePassword)
    if [ "$P1" == "$WLAN_SSID" ] ; then
      WLAN_PASSWORD="$P3"
      WLAN_PASSWORD_METHOD="$P4"
      writeServerConf
    fi
		echo "OK"
    ;;
  mode)
	  getWlanMode;
  	echo $wlanmode
	  ;;
  ap)
	  ./activateAP &> /dev/null
	  echo "OK"
	  ;;
  disableAp)
	  prepareConnect &> /dev/null
	  ;;
  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)
    echo "ipv4_method:$ETH_4_MODE"
    echo "ipv4_addresses:$ETH_4_STATIC"
    echo "ipv4_gateway:$ETH_4_GATEWAY"
    echo "ipv4_dns:$ETH_4_DNS"
    echo "ipv6_method:$ETH_6_MODE"
    echo "ipv6_addresses:$ETH_6_STATIC"
    echo "ipv6_gateway:$ETH_6_GATEWAY"
    echo "ipv6_dns:$ETH_6_DNS"
    ;;
  ethUpdate)
    updateDHCPCD
    ;;
  ethIP4Auto)
    ETH_4_MODE="auto"
    ETH_4_STATIC="$P1"
    ETH_4_DNS="$P3"
    ETH_4_GATEWAY="$P2"
    writeServerConf
    ;;
  ethIP6Auto)
    ETH_6_MODE="auto"
    ETH_6_STATIC="$P1"
    ETH_6_DNS="$P3"
    ETH_6_GATEWAY="$P2"
    writeServerConf
    ;;
  ethIP4Manual)
    ETH_4_MODE="manual"
    ETH_4_STATIC="$P1"
    ETH_4_DNS="$P3"
    ETH_4_GATEWAY="$P2"
    writeServerConf
    ;;
  ethIP6Manual)
    ETH_6_MODE="manual"
    ETH_6_STATIC="$P1"
    ETH_6_DNS="$P3"
    ETH_6_GATEWAY="$P2"
    writeServerConf
    ;;
  *)
	echo "Unknown command $CMD"
	;;
esac

