#!/bin/bash

log_file="/root/wifi-start.log"

log_message() {
    # echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$log_file"
    echo "$1"
}


add_unmanaged_eth0() {
  local conf_file="/etc/NetworkManager/NetworkManager.conf"
  local keyfile_section="[keyfile]"
  local unmanaged_devices="unmanaged-devices=interface-name:eth0"
  local to_append="$keyfile_section\n$unmanaged_devices"

  # Check if the string is already in the file.
  if ! grep -Fq "$unmanaged_devices" "$conf_file"; then
      echo -e "\n$to_append" | tee -a "$conf_file" > /dev/null
      log_message "Configuration added and NetworkManager will be restarted."
  else
      log_message "Configuration already exists. No changes made."
  fi
}

log_message " "
log_message " "
log_message "*********************************"
log_message "Running wifi-start"
log_message "*********************************"
log_message "Arguments:"
for arg in "$@"
do
  log_message "    $arg"
done

add_unmanaged_eth0

MODE=WIFI_P2P
FILE=/etc/lcriq.conf
FILELCRIQNAME=/etc/lcriqname
FILELCRIQPASSWORD=/etc/lcriqpassword
FILELCRIQIP=/etc/lcriqip
FILELCRIQIPCONF=/etc/lcriqip.conf
RESTARTING=false

if test -f "$FILE"; then
    MODE=`cat $FILE`
fi

if test -f "$FILELCRIQNAME"; then
    LCRIQNAME=`cat $FILELCRIQNAME`
else
    LCRIQNAME=""
fi

if test -f "$FILELCRIQPASSWORD"; then
    LCRIQPASSWORD=`cat $FILELCRIQPASSWORD`
else
    LCRIQPASSWORD=""
fi

if test -f "$FILELCRIQIP"; then
    LCRIQIP=`cat $FILELCRIQIP`
else
    LCRIQIP=""
fi
log_message "LCRIQIP is $LCRIQIP"

if test -f "$FILELCRIQIPCONF"; then
    LCRIQIPCONF=`cat /etc/lcriqipeth.conf`
    log_message "Loaded LCRIQIPCONF from file"
else
    LCRIQIPCONF="0.0.0.0"
fi

log_message "LCRIQIPCONF is $LCRIQIPCONF"
log_message "Mode is $MODE"

case $MODE in
  WIFI_AP)
    log_message "WiFi mode AP"
    ;;
  WIFI_STA)
    log_message "WiFi mode STA"
    ;;
  WIFI_P2P)
    log_message "WiFi mode P2P"
    ;;
  ETH_STA)
    log_message "ETH mode STA"
    ;;
  ETH_DYN)
    log_message "ETH mode DYN"
    ;;
  WIFI_ETH_STA)
    log_message "NET mode Dual WIFI ETHERNET"
    ;;
  NET_OFF)
    log_message "NET mode OFF"
    ;;
  WIFI_ETH_P2P)
    log_message "ETHERNET with Hotspot"
    ;;
  *)
    MODE=NET_OFF
    log_message "Invalid Network mode switching to default"
    ;;
esac

# Stop Ethernet
log_message "Stopping Ethernet"
/sbin/ifconfig eth0 down

# Stop WiFi
log_message "Stopping WiFi"
#systemctl stop sr1000-ttyV0
#systemctl stop sr1000-ttyV1
systemctl disable wpa_supplicant
systemctl stop wpa_supplicant
/sbin/ifconfig wlan0 down
/usr/bin/nmcli radio wifi off
/usr/bin/killall -s 9 udhcpd
/usr/bin/killall -s 9 /sbin/wpa_supplicant

############################################################################
#
#This is the last step before setting the wifi and dhcp. Make sure all
#parameters are validated and entered correctly from the console before
#calling this script.
#
#############################################################################

# If any parameter is missing do the defaults

if [ -z $1 ] || [ -z $2 ] || [ -z $3 ]
then

  macw=$(cat /sys/class/net/eth0/address)
  psk="$(echo $macw | tr -d ':')"
  macw=${macw//:/-}

  log_message "Setting the default IPAddr"

  ssid="LCRIQ-$macw"
  if [ -z "$LCRIQIP" ]; then
    log_message "Using 192.168.1.30"
    IPAddr=192.168.1.30
  else
    IPAddr="$LCRIQIP"
    log_message "Using $IPAddr"
  fi


  if [ -z $1 ] && [ -z $2 ] && [ -z $3 ]
  then
    log_message "Creating SSID and Password"

    if [ "$LCRIQNAME" != "" ]; then
      ssid=$LCRIQNAME
    fi

    if [ "$LCRIQPASSWORD" != "" ]; then
      psk=$LCRIQPASSWORD
    fi
  else
    log_message "Resetting SSID and Password"
  fi
else
  log_message "Setting SSID and Password"

  ssid="$1"
  psk="$2"
  IPAddr=$3

  RESTARTING=true
fi

ssidstring=ssid="\"$ssid\""
pskstring=psk="\"$psk\""

# Log arguments
log_message "SSID          :  $ssid"
log_message "PSWD          :  $psk"
log_message "START UP IP   :  $IPAddr"

# Edit wpa configuration
log_message "SSID String   :  $ssidstring"
log_message "PSWD String   :  $pskstring"

/bin/sed -i '/ssid/c\'"  $ssidstring" /etc/wpa_supplicant.conf
/bin/sed -i '/psk/c\'"  $pskstring" /etc/wpa_supplicant.conf

log_message "Saving hostname"
log_message "$ssid" > $FILELCRIQNAME

log_message "Saving password"
log_message "$psk" > $FILELCRIQPASSWORD

log_message "Saving IP address"
log_message "$IPAddr" > $FILELCRIQIP

log_message "Set hostname"

# Set hostname
hostnamectl set-hostname $ssid

# Restart bluetooth
systemctl restart bluetooth

if [ "$MODE" == "WIFI_P2P" ]; then

  log_message "Starting UDHCPD"
  systemctl disable dnsmasq
  systemctl stop dnsmasq
  iptables -F
  iptables -t nat -F

  /usr/sbin/udhcpd -S -I $IPAddr

  log_message "Starting WAP_SUPPLICANT in P2P mode"

  /sbin/wpa_supplicant -qq -Dnl80211 -iwlan0 -c/etc/wpa_supplicant.conf &

  log_message "Assigning wlan0"

  /sbin/ifconfig wlan0 $IPAddr

  log_message "Bringing wlan0 online"
  /sbin/ifconfig wlan0 up

elif [ "$MODE" == "WIFI_STA" ]; then
  log_message "Starting WAP_SUPPLICANT in STA mode"
  systemctl disable dnsmasq
  systemctl stop dnsmasq
  iptables -F
  iptables -t nat -F

  systemctl enable wpa_supplicant
  systemctl start wpa_supplicant
  nmcli radio wifi on
  if [ "$IPAddr" == "0.0.0.0" ]; then
    log_message "Using DHCP"
    systemctl restart NetworkManager.service
    log_message "Bringing wlan0 online"
    ip addr flush dev wlan0
    /etc/init.d/networking restart
    /sbin/ifconfig wlan0 up
    /sbin/dhclient wlan0 &
  else
    log_message "Assigning IP address $IPAddr to wlan0"
    /sbin/ifconfig wlan0 $IPAddr up
  fi
elif [ "$MODE" == "ETH_STA" ]; then

  log_message "Starting ETH in STA mode"
  systemctl disable dnsmasq
  systemctl stop dnsmasq
  iptables -F
  iptables -t nat -F

  if [ "$LCRIQIPCONF" == "0.0.0.0" ]; then
    log_message "Using DHCP"
    systemctl restart NetworkManager.service
    log_message "Bringing eth0 online"
    ip addr flush dev eth0
    /etc/init.d/networking restart
    /sbin/ifconfig eth0 up
    /sbin/dhclient eth0 &
  else
    log_message "Disable DHCP client"
    systemctl stop NetworkManager.service
    log_message "Assigning IP address $LCRIQIPCONF to eth0"
    /sbin/ifconfig eth0 $LCRIQIPCONF up
  fi
elif [ "$MODE" == "ETH_DYN" ]; then

  log_message "Starting ETH in Dynamic mode"
  systemctl disable dnsmasq
  systemctl stop dnsmasq
  iptables -F
  iptables -t nat -F

  if [ "$LCRIQIPCONF" == "0.0.0.0" ]; then
    log_message "Using DHCP"
    systemctl restart NetworkManager.service
    log_message "Bringing eth0 online"
    ip addr flush dev eth0
    /etc/init.d/networking restart
    /sbin/ifconfig eth0 up
    /sbin/dhclient eth0 &
  else
    log_message "Disable DHCP client"
    systemctl stop NetworkManager.service
    ip addr flush dev eth0
    log_message "Assigning IP address $LCRIQIPCONF to eth0"
    /sbin/ifconfig eth0 $LCRIQIPCONF up
  fi

elif [ "$MODE" == "WIFI_ETH_STA" ]; then
  log_message "Using Both WIFI and Ethernet in STA mode"

  systemctl disable dnsmasq
  systemctl stop dnsmasq
  iptables -F
  iptables -t nat -F

  log_message "Starting WAP_SUPPLICANT in STA mode"

  systemctl enable wpa_supplicant
  systemctl start wpa_supplicant

  nmcli radio wifi on
  if [ "$IPAddr" == "0.0.0.0" ]; then
    log_message "Using DHCP"
    systemctl restart NetworkManager.service
    log_message "Bringing wlan0 online"
    ip addr flush dev wlan0
    ip addr flush dev eth0
    /etc/init.d/networking restart
    /sbin/ifconfig wlan0 up
    /sbin/dhclient wlan0 &
    /sbin/ifconfig eth0 up
    /sbin/dhclient eth0 &
  else
    #Note that in the future we may need to be able to assign IP addresses to both wlan0 and eth0
    log_message "Assigning IP address $IPAddr to wlan0"
    /sbin/ifconfig wlan0 $IPAddr up
  fi
  if [ "$LCRIQIPCONF" == "0.0.0.0" ]; then
    log_message "Using Dynamic Ethernet IP Address"
    /sbin/ifconfig eth0 up
    /sbin/dhclient eth0 &
  else
    log_message "Assigning IP address $LCRIQIPCONF to eth0"
    /sbin/ifconfig eth0 $LCRIQIPCONF up
  fi
elif [ "$MODE" == "WIFI_ETH_P2P" ]; then
  log_message "Using WIFI for hotspot and Ethernet in STA mode"
  systemctl disable dnsmasq
  systemctl stop dnsmasq
  log_message "Using DHCP"
 

  if [ "$LCRIQIPCONF" == "0.0.0.0" ]; then
    log_message "Using Dynamic Ethernet IP Address"
    systemctl restart NetworkManager.service
    log_message "Bringing eth0 online"
    ip addr flush dev eth0
    /etc/init.d/networking restart
    /sbin/ifconfig eth0 up
    /sbin/dhclient eth0 &
  else
    log_message "Assigning IP address $LCRIQIPCONF to eth0"
    /sbin/ifconfig eth0 $LCRIQIPCONF up
  fi

  iptables -F
  iptables -t nat -F

  log_message "Starting WAP_SUPPLICANT in P2P mode"
  /sbin/wpa_supplicant -qq -Dnl80211 -iwlan0 -c/etc/wpa_supplicant.conf &
  log_message "Assigning wlan0"
  /sbin/ifconfig wlan0 192.168.30.1
  log_message "Bringing wlan0 online"
  /sbin/ifconfig wlan0 up

  sysctl -w net.ipv4.ip_forward=1
  iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
  iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

  # ip link set up dev wlan0
  systemctl enable dnsmasq
  systemctl restart dnsmasq

else
  log_message "Network is OFF"

fi

if [ "$RESTARTING" == "true" ]; then
# Restart sr1000-ttyVs
  systemctl restart sr1000-ttyV0
  systemctl restart sr1000-ttyV1
  systemctl restart sr1000-rfcomm
fi
