#!/bin/sh

command="$1"
[ -z "$command" ] && exit

ROOT=/www
CONFIG=$ROOT/config
SCRIPT=$ROOT/script

source $CONFIG/ng.conf
source $CONFIG/ap.conf
source $CONFIG/api.conf
source $CONFIG/mqtt.conf
source $SCRIPT/utils/network.sh
source $SCRIPT/utils/wifi.sh
source $SCRIPT/utils/wifi-extend.sh

DEVICE_ID="$bishbosh_connect_username"

commandGeneral="command/$DEVICE_ID"
commandKick="sessions/kick/$DEVICE_ID"
commandUpdateApiConfig="config/update/api/$DEVICE_ID"
commandUpdateNgConfig="config/update/ng/$DEVICE_ID"
commandUpdateCode="config/update/code/$DEVICE_ID"

reboot() {
  echo "rebooting"
  /sbin/reboot -f -d 3 &
}

networkInfo() {
  echo "routing table"
  ip ro
  echo
  echo "interfaces"
  ifconfig
  echo
  echo "iptables rules"
  iptables -t nat -vnxL
  iptables -t mangle -vnxL
  iptables -vnxL
  echo
  echo "ipset"
  ipset list
}

wifiInfo() {
  echo "airing ssids"
  iwinfo
  echo
  echo "connected clients"
  local ssids=`getEnabledSsidList`
  local radios=`getRadioCount`
  local index=0
  for ssid in $ssids ; do
    index=$((index + 1))
    for radio in `seq 1 $radios` ; do
      mode=`getRadioMode $radio`
      [ ! -n "$mode" ] && mode=2G
      echo "ssid $ssid mode $mode"
      getStationList $index $ssid $radio
      echo
    done
  done
  echo
}

getConfig() {
  echo "network config"
  uci show network
  echo
  echo "wireless config"
  uci show wireless
  echo
  echo "dhcp config"
  uci show dhcp
  echo
  echo "uhttpd config"
  uci show uhttpd
}

getVersion() {
  echo "OpenWRT version"
  cat /etc/openwrt_release | grep DISTRIB_DESCRIPTION | cut -d "'" -f 2
  echo
  echo "Code version"
  cat /www/version
  echo
  cat /etc/code_checksum 2>/dev/null
}

general() {
  command="$1"
  case "$command" in
  "reboot")
    reboot
    ;;
  "networkInfo")
    networkInfo
    ;;
  "wifiInfo")
    wifiInfo
    ;;
  "getConfig")
    getConfig
    ;;
  "updateConfig")
    sh "$SCRIPT/update/update-ng-config.sh"
    ;;
  "getVersion")
    getVersion
    ;;
  "updateCode")
    sh "$SCRIPT/update/update-code.sh"
    ;;
  "restartServices")
    /etc/init.d/ng_ap2 restart
    /etc/init.d/uhttpd restart
    /etc/init.d/dnsmasq restart
    ;;
  "getPublicIp")
    wget -T 5 -qO- icanhazip.com
    ;;
  *)
    echo "not supported command"
    echo "not supported command" >&2
    ;;
  esac
}

kickSession() {
  local sessionInfo="$1"
  [ -z "$sessionInfo" ] && exit
  echo "kick session $sessionInfo"
  eval "$sessionInfo $SCRIPT/session/logout.sh"
}

case "$command" in
  "$commandGeneral")
    general "$2"
    ;;
  "$commandKick")
    kickSession "$2"
    ;;
  "$commandUpdateNgConfig")
    sh "$SCRIPT/update/update-ng-config.sh"
    ;;
  "$commandUpdateCode")
    sh "$SCRIPT/update/update-code.sh"
    ;;
  "$commandUpdateApiConfig")
    cloudAddress="$2"
    [ -z "$cloudAddress" ] || sh "$SCRIPT/update/update-api-config.sh" "$cloudAddress"
    ;;
  *)
    echo "not supported command" >&2
    ;;
esac
