#!/bin/bash

source /etc/netconnect/netconnect.conf

_usage () {
   echo "Usage: netconnect[ -d DIR ... ] OPTION"
   echo "   OPTION can be:  status | l(ist) | d(isconnect) | cable | CONNECTION | usb | s | scan | ssh | menu | new "
   echo "Usage: netconnect [ -h | --help ]"
   echo "Usage: netconnect [ -v | --version ]"
}


_moreetchosts () {
   if [ -d /etc/hosts.d ]; then
     for ff in `find /etc/hosts.d -maxdepth 1 -type f`; do
        cat $ff >> /etc/hosts
     done
   fi
}

_etchosts () { # $1 is connection ("disconnect", if empty)
   FILE="`find $WDIRS -type f -name "$1.hosts" | head -1`"
   FE=/etc/netconnect/con/disconnect.hosts
   if [ ! -z "$FILE" -a -f "$FILE" ]; then
      cp -v $FILE /etc/hosts
   elif [ -f "$FE" ]; then
      cp -v $FE /etc/hosts
   else
      echo "127.0.0.1       `hostname` localhost" > /etc/hosts
   fi
   _moreetchosts
}

_newconnection () { # $1 is directory (optional)
   if [ -z "$1" ]; then
       D="`echo $WDIRS | awk '{print $1}'`"
   else
       D=$1
   fi
   echo "Creating new connection in $D/..."
   echo -n "Connection name: "
   read NN
   echo -n "SSID: "
   read SSID
   echo "Password:"
   mkdir -p $D
   wpa_passphrase "$SSID" > $D/$NN.wpa
   echo "New connection $NN in $D/$NN.wpa created:"
   cat $D/$NN.wpa
}

_version () {
   echo "netconnect Version 0.5"
}

_firewalloff () {
   # A Hack for taking care of mlx
   if [ "`realpath /etc/firewall/firewall`" =  "/etc/firewall/firewall.mlx" ]; then
      firewall mlx
   else
      firewall off
   fi
}

if [ "$1" = "-h" -o "$1" = "--help" ]; then
   _usage
   exit 17
fi

if [ "$1" = "-v" -o "$1" == "--version" ]; then
   _version
   exit 17
fi

if [ `whoami` != root ]; then
   if [ "$1" = "new" ]; then
      _newconnection $HOME/.netconnect
   else
      sudo $0 -d $HOME/.netconnect $*
   fi
else

   WDIRS=""
   while [ "$1" = "-d" ]; do
      WDIRS="$WDIRS $2"
      shift; shift
   done
   WDIRS="$WDIRS /etc/netconnect/con"

_resolvconfempty () {
   echo "" > /etc/resolv.conf
}

_disconnectnfs () {
    for DIR in `mount | grep '\bnfs[0-9]*\b' | awk '{print $3}'`; do
        for P in `lsof 2> /dev/null | grep "$DIR\b" | awk '{print $2}' | sort -u`; do ps augxww | grep -v grep | grep $P; kill $P; done
        for P in `lsof 2> /dev/null | grep "$DIR\b" | awk '{print $2}' | sort -u`; do ps augxww | grep -v grep | grep $P; kill -9 $P; done
        umount -v -f $DIR
    done
}

_disconnect () {
  # if [ -x /usr/bin/sshtunnel-stop ]; then /usr/bin/sshtunnel-stop; fi
  _disconnectnfs
  killall -v socat 
  killall -v ssh
  dhclient -v -r
  killall -v wpa_supplicant
  for I in `/bin/ls -d /sys/class/eth* /sys/class/net/enp* /sys/class/net/enx* /sys/class/net/wl* 2>/dev/null`; do
     ip link set dev `basename $I` down
  done
  _firewalloff
  _etchosts
  _resolvconfempty
}

_wlanconnect () { #$1 = filename # old: #$1 is netname, $2 is filename in /etc/wpa
   ssid="`cat $1 | awk -F'#' '{print $1}' | grep 'ssid=' | sed '1,$ s/\"//g' | awk -F= '{print $2}'`"
   set -x
   ip link set $WLAN up
   iw dev $WLAN connect "$ssid"
   wpa_supplicant -B -D nl80211 -i $WLAN -c $1
   sleep 1
   dhclient -v $WLAN
   firewall
   set +x
}

_shell () { # $1 is connection
   FILE="`find $WDIRS -type f -name $1.sh | head -1`"
   if [ ! -z "$FILE" -a -f "$FILE" ]; then
      # shell file must take care of firewall!
      source $FILE
   else
      echo "no $1.sh found"
   fi
}

_shellw () { # $1 is connection
   FILE="`find $WDIRS -type f -name $1.sh | head -1`"
   if [ ! -z "$FILE" -a -f "$FILE" ]; then
      # shell file must take care of firewall!
      source $FILE
   else
      WP="`find $WDIRS -type f -name $1.wpa | head -1`"
      if [ ! -z "$WP" -a -f "$WP" ]; then
        _wlanconnect $WP
      fi
      _etchosts $1
   fi
}

if [ $# = 0 -o "$1" = "-h" ]; then
   _usage
   exit 0
elif [ "$1" = "st" -o "$1" = "status" ]; then
   netmon
elif [ "$1" = "l" -o "$1" = "list" ]; then
   find $WDIRS -type f -exec basename {} \; | cut -d . -f 1 | grep -v disconnect | sort -u
elif [ "$1" = "m" -o "$1" = "menu" ]; then
   WDIRSOPT="`echo $WDIRS | awk '{for(i=1;i<=NF;i++)printf " -d %s",$i}END{printf "\n"}'`"
   ( 
   echo backtitle "\"Connection Menu\""
   echo title "\"Select connection:\""
   echo tty "`tty`"
   echo "st  status \"netmon\""
   echo "d  disconnect \"netconnect disconnect\""
   echo "dn  \"disconnect nfs\" \"netconnect dnfs\""
   echo "l  list       \"netconnect $WDIRSOPT list\""
   echo "n  \"new connection\" \"netconnect $WDIRSOPT new\""
   if [ -x /usr/bin/sshtunnel ]; then
      echo "ssh \"sshtunnel\" \"sshtunnel\""
   fi
   echo "s  \"scan brief\" \"netconnect s\""
   echo "sc \"scan full\"  \"netconnect scan\""
   echo "op \"open wlan\"  \"netconnect.openwlan\""
   c=0
   for X in `find $WDIRS -type f -exec basename {} \; | cut -d . -f 1 | grep -v disconnect | sort -u`; do
      echo "$c $X \"netconnect $WDIRSOPT $X\""
      c=$((c+1))
   done
   #      awk 'BEGIN {c=0} {print c,$1,".","\"netconnect $WDIRSOPT $1\""; c++}'
   ) | mmenu
elif [ "$1" = "new" ]; then
   _newconnection
elif [ "$1" = "d" -o "$1" = "disconnect" ]; then
   _disconnect
elif [ "$1" = "dn" ]; then
   _disconnectnfs
elif [ "$1" = cable ]; then
   _disconnect
   _shell cable # must take care of firewall!
elif [ "$1" = ssh ]; then
   # dont _disconnect
   if [ -x /usr/bin/sshtunnel ]; then
      /usr/bin/sshtunnel
   fi
elif [ "$1" = "s" ]; then
   if ip link show | grep $WLAN | grep DOWN > /dev/null; then
      set -x
      ip link set $WLAN up
      iw $WLAN scan | egrep '^BSS|freq:|SSID:|signal:'
      ip link set $WLAN down
      set +x
   elif ip link show | grep $WLAN | grep UP > /dev/null; then
      set -x
      iw $WLAN scan | egrep '^BSS|freq:|SSID:|signal:'
      set +x
   else
      _disconnect
      set -x
      ip link set $WLAN up
      iw $WLAN scan | egrep '^BSS|freq:|SSID:|signal:'
      ip link set $WLAN down
      set +x
      _etchosts # takes disconnect
   fi
elif [ "$1" = "scan" ]; then
   if ip link show | grep $WLAN | grep DOWN > /dev/null; then
      set -x
      ip link set $WLAN up
      iw $WLAN scan
      ip link set $WLAN down
      set +x
   elif ip link show | grep $WLAN | grep UP > /dev/null; then
      set -x
      iw $WLAN scan
   else
      _disconnect
      set -x
      ip link set $WLAN up
      iw $WLAN scan
      ip link set $WLAN down
      set +x
      _etchosts
   fi
elif [ "$1" = "op" ]; then
   netconnect.openlwan
else
   _disconnect
   _shellw $1
fi

fi
