#!/bin/bash

function main()
{
  echo
  case "$1" in
    'config'              )        Run_Splashtop_config "$@" ;;
    'debug'               )        Run_Splashtop_debug "$@" ;;
    'deploy'              )        Run_Splashtop_deploy "$@" ;;
    '-h'                  )        Run_Splashtop_help "$@" ;;
    'help'                )        Run_Splashtop_help "$@" ;;
    '-help'               )        Run_Splashtop_help "$@" ;;
    '--help'              )        Run_Splashtop_help "$@" ;;
    'version'             )        Run_Splashtop_help "$@" ;;
    '-version'            )        Run_Splashtop_help "$@" ;;
    '--version'           )        Run_Splashtop_help "$@" ;;
    'daemon'              )        Run_Splashtop_daemon "$@" ;;
    'auto'                )        Run_Splashtop_gui_auto "$@" ;;
    *                     )        Run_Splashtop_gui "$@" ;;
  esac
  echo
}

function Init()
{
  #SPT_DIR="$(dirname "$SPT_SCR_DIR")"
  export LD_LIBRARY_PATH=$SPT_DIR
}

function InitGui()
{
  # To enable AppIndicator on Gnome3 with Wayland
  export GDK_BACKEND=x11
}

function LockStartup()
{
  exec 300>> "/dev/null" || echo "LockStartup: internal error $?"
  if flock -n 300
  then
    return 0
  else
    return 1
  fi
}

function UnlockStartup()
{
    flock -u -n 300
    exec 300<&-
}

function Check_daemon()
{
  case "$(pidof SRFeature | wc -w)" in
    0) echo "Starting SRFeature....."
      return 0
      ;;
    1) echo "SRFeature is running...."
      return 1
      ;;
    *) echo "Stopping SRFeature..."
      kill $(pidof SRFeature | awk '{print $1}')
      ;;
  esac
}

function Run_Splashtop()
{
  Init
  InitGui
  LockStartup
  retval=$?
  if [ "$retval" -eq 0 ]
  then
    $SPT_DIR/SRFeature&
  fi
  echo "Launch streamer ..."
  $SPT_DIR/SRStreamer
  UnlockStartup
}

function Run_Splashtop_daemon()
{
  Init
  Check_daemon
  retval=$?
  if [ "$retval" -eq 0 ]; then
    $SPT_DIR/SRFeature
  else
    exit 1
  fi
}

function Run_Splashtop_gui()
{
  InitGui

  echo "$@"
  if [ ! -f $SPT_DIR/SRStreamer ]; then
    echo "The installed Streamer does not include GUI frontend."
    Run_Splashtop_help
    return 1
  fi

  LockStartup
  retval=$?
  if [ "$retval" -eq 0 ]; then
    echo "Streamer is not running"
  else
    echo "Streamer is already running $?"
  fi

  echo "Launch streamer UI ..."
  if [ -f "/opt/splashtop-streamer/config/global.conf" ]; then
      sed -i -e "s/"HideWindow=1"/"HideWindow=0"/" /opt/splashtop-streamer/config/global.conf
  fi

  $SPT_DIR/SRStreamer

  UnlockStartup
}

function Run_Splashtop_gui_auto()
{
  InitGui

  if [ ! -f $SPT_DIR/SRStreamer ]; then
    echo "The installed Streamer does not include GUI frontend."
    Run_Splashtop_help
    return 1
  fi

  LockStartup
  retval=$?
  if [ "$retval" -eq 0 ]; then
    echo "Streamer is not running"
  else
  echo "Streamer is already running $?"
  fi
  if [ -f "/opt/splashtop-streamer/config/global.conf" ]; then
      sed -i -e "s/"HideWindow=0"/"HideWindow=1"/" /opt/splashtop-streamer/config/global.conf
  fi

  $SPT_DIR/SRStreamer
  UnlockStartup
}

function Run_Splashtop_help()
{
  if [[ "version" == "$1" ]] || [[ "-version" == "$1" ]] || [[ "--version" == "$1" ]]; then
    if [[ ! -f $SPT_DIR/SRUtility ]]; then
      echo "Please uninstall then reinstall newer version."
      return 1
    fi
    $SPT_DIR/SRUtility -version
  else
    echo "Streamer Commands"
    echo "Usage:"
    echo "splashtop-streamer [COMMAND] <help|config|deploy|debug|version>"
    echo "Type splashtop-streamer [COMMAND] for more information"
  fi
}

function Run_Splashtop_deploy()
{
  echo "Streamer Deployment"
  if [[ ! -f $SPT_DIR/SRUtility ]]; then
    echo "  Deploy Fail. Please uninstall then reinstall newer version."
    return 1
  fi

  dcode=""
  srvid=""
  if [ -f "/opt/splashtop-streamer/config/global.conf" ]; then
    srvid=$(cat /opt/splashtop-streamer/config/global.conf | grep CloudServerID= | cut -d'=' -f2)
  fi

  if [[ "245" == "$srvid" ]]; then
    gateway=""
    if [ $# -eq 3 ]; then
      echo "  Gateway: $2"
      gateway=$2
      echo "  Code: $3"
      dcode=$3
    else
      echo "  splashtop-streamer deploy [GATEWAY] [CODE]"
      echo "  Enter gateway address."
      read -p "  Addr: " gateway
      echo "  Enter code from your admin to allow access to this computer."
      read -p "  Code: " dcode
    fi
    gw_proto=$(echo $gateway | grep '://')
    if [[ $gw_proto == "" ]]; then
      gw_proto=""
      gw_url=`echo $gateway`
    else
      gw_proto="`echo $gateway | grep '://' | sed -e's,^\(.*://\).*,\1,g'`"
      gw_url=`echo $gateway | sed -e s,$gw_proto,,g`
    fi
    gw_userpass="`echo $gw_url | grep @ | cut -d@ -f1`"
    gw_hostport=`echo $gw_url | sed -e s,$gw_userpass@,,g | cut -d/ -f1`
    gw_port=`echo $gw_hostport | grep : | cut -d: -f2`
    if [ -n "$gw_port" ]; then
      gw_host=`echo $gw_hostport | grep : | cut -d: -f1`
    else
      gw_host=$gw_hostport
      gw_port="443"
    fi
    gw_conf=$(cat /opt/splashtop-streamer/config/global.conf | grep CloudUserServer)
    if [[ $gw_conf == "" ]]; then
      echo "CloudUserServer=$gw_host" >> /opt/splashtop-streamer/config/global.conf
      echo "CloudUserPort=$gw_port" >> /opt/splashtop-streamer/config/global.conf
    else
      sed -i 's,^CloudUserServer=.*$,CloudUserServer='$gw_host',' /opt/splashtop-streamer/config/global.conf
      sed -i 's,^CloudUserPort=.*$,CloudUserPort='$gw_port',' /opt/splashtop-streamer/config/global.conf
    fi
  else
    if [ $# -eq 2 ]; then
      echo "  Code: $2"
      dcode=$2
    else
      echo "  splashtop-streamer deploy [CODE]"
      echo "  Enter code from your admin to allow access to this computer."
      read -p "  Code: " dcode
    fi
  fi

  if [[ $(id -u) -eq 0 ]]; then
    systemctl stop SRStreamer
  fi

  if [[ $(id -u) -eq 0 ]]; then
    $SPT_DIR/SRUtility -deployment $dcode
  else
    $SPT_DIR/SRUtility -deployment $dcode -rootless
  fi

  if [ $? = "0" ]; then
    echo "  This deployment package is invalid."
    echo "  Please uninstall then reinstall or contact your admin."
  else
    echo "  Deploy Success"
  fi

  if [[ $(id -u) -eq 0 ]]; then
    systemctl restart SRStreamer
  fi

  sys_os=$(cat /opt/splashtop-streamer/config/global.conf | grep SysOSName)
  if [[ $sys_os == "" ]]; then
    sys_name="$(cat /etc/os-release | sed -n -e 's/^\s*NAME\s*=\s*//p' | sed 's/"//g')"
    sys_version="$(cat /etc/os-release | sed -n -e 's/^\s*VERSION_ID\s*=\s*//p' | sed 's/"//g')"
    echo "SysOSName=$sys_name $sys_version" >> /opt/splashtop-streamer/config/global.conf
  fi
}

function Run_Splashtop_debug()
{
  echo "Streamer Debug"
  cmd=""
  if [ $# -eq 1 ]; then
    echo "  splashtop-streamer debug [OPTION] <upload|level|site>"
  else
    cmd=$2
  fi

  if [[ ! -f $SPT_DIR/SRUtility ]]; then
    echo "Fail to " $cmd
    return 1
  fi

  if [[ "$cmd" == "upload" ]]; then
    $SPT_DIR/SRUtility -uploadlog
    if [ $? = "0" ]; then
      echo "Log upload fail."
    else
      echo "Log upload success."
    fi
  fi

  if [[ "$cmd" == "level" ]]; then

    $SPT_DIR/SRUtility -dblevel $3
    echo "Level changed."
  fi

  if [[ "$cmd" == "site" ]]; then
    $SPT_DIR/SRUtility -dbsite $3

    echo "Site changed."
  fi
}

function Run_Splashtop_config_usage()
{
  if [[ "all" == "$1" ]]; then
    echo "Usage: splashtop-streamer config [options]"
    echo "Options:"
  fi

  if [[ "all" == "$1" ]] || [[ "$1" == "devname" ]]; then
    echo "  -devname=<arg>      Streamer Name"
    echo "                        No encoding character, UTF8/unicode"
    echo "                        Maximum 64 characters, exclude < > , ; : \" * + = \\ | ? "
  fi

  if [[ "all" == "$1" ]] || [[ "$1" == "resetuuid" ]]; then
    echo "  -resetuuid          Regenerate Streamer ID"
  fi

  if [[ "all" == "$1" ]] || [[ "$1" == "securitycode" ]] || [[ "$1" == "sec_code" ]]; then
    echo "  -securitycode=<arg> Security code"
    echo "  -sec_code=<arg>       8 to 20 characters. Letters and numbers only."
    echo "                        Must contain at least one letter and one number."
  fi

  if [[ "all" == "$1" ]] || [[ "$1" == "sec_opt" ]]; then
    echo "  -sec_opt=<option>   Security option"
    echo "                        0:No additional password"
    echo "                        1:Require security code"
    echo "                        2:Require system login"
  fi

#  if [[ "all" == "$1" ]] || [[ "$1" == "sound" ]]; then
#    echo "  -sound=<option>     Sound option"
#    echo "                        0:Local computer only"
#    echo "                        1:Output to client device"
#  fi

  if [[ "all" == "$1" ]] || [[ "$1" == "list" ]]; then
    echo "  -list               List all configutation"
  fi
}

function Run_Splashtop_config()
{
  echo "Streamer Configuration"

  if [ $# -eq 1 ]; then
    Run_Splashtop_config_usage "all"
    return 1
  fi

  if [ $# -ne 2 ]; then
    Run_Splashtop_config_usage "all"
    echo "One command at a time."
    return 1
  fi

  if [[ ! -f $SPT_DIR/SRUtility ]]; then
    echo "Fail ot config. Please reinstall streamer."
    return 1
  fi

  cmd=$(echo $2|cut -d'=' -f1)
  val=""
  if [[ "$2" == *"="* ]]; then
    val=$(echo $2|cut -d'=' -f2)
  fi

  if [[ "$cmd" == "-devname" ]]; then
    if [ "" == "$val" ]; then
      Run_Splashtop_config_usage "devname"
      return 1
    fi

    if [[ $val =~ "<>,;:\"*+=\\|?" ]]; then
      Run_Splashtop_config_usage "devname"
      return 1
    fi

    if [[ ${#val} -gt 64 ]]; then
      Run_Splashtop_config_usage "devname"
      return 1
    fi

    echo "Set streamer Name" $val
  elif  [[ "$cmd" == "-resetuuid" ]]; then
    echo "Reset Streamer ID"
    if [ -f "/opt/splashtop-streamer/config/global.conf" ]; then
      val=$(cat /opt/splashtop-streamer/config/global.conf | grep ServerUUID= | cut -d'=' -f2)
    fi
  elif  [[ "$cmd" == "-securitycode" ]] || [[ "$cmd" == "-sec_code" ]]; then
    if [ "" == "$val" ]; then
      Run_Splashtop_config_usage "securitycode"
      return 1
    fi

    if [[ $val =~ [^0-9A-Za-z] ]]; then
      Run_Splashtop_config_usage "securitycode"
      return 1
    fi

    if [[ ${#val} -lt 8 ]] || [[ 20 -lt ${#val} ]]; then
      Run_Splashtop_config_usage "securitycode"
      return 1
    fi

    echo "Set security code" $val
  elif  [[ "$cmd" == "-sec_opt" ]]; then
    if [ "" == "$val" ]; then
      Run_Splashtop_config_usage "sec_opt"
      return 1
    fi

    echo "Set security option" $val
  elif  [[ "$cmd" == "-sound" ]]; then
    if [ "" == "$val" ]; then
      Run_Splashtop_config_usage "sound"
      return 1
    fi

    echo "Set sound option" $val
  elif  [[ "$cmd" == "-list" ]]; then
    val="all"
  else
    Run_Splashtop_config_usage "all"
    return 1
  fi

  command="${cmd##-}"
  $SPT_DIR/SRUtility -settings $command $val
}
