#!/usr/bin/env bash

NODE_PCK_DOWNLOAD_URL="https://ftp.speedtest.cn/node/"
INSTALL_DIR=""
SERVER_PCK=""
LOCAL_PCK="speedtest-node"
JAVA_ENV="./jre/bin/java"

#color
RED='\e[31m '
GREEN='\e[32m '
NC='\e[0m'


display_usage() {
  echo "This script can be used to install or control a Speedtest-node Server"
  echo "Usage:"
  echo "$0 command"
  echo ""
  echo "  Valid commands: install, start, stop, restart"
  echo "    install         - downloads and installs the Speedtest-node Server"
  echo "    start           - starts the server if not running"
  echo "    stop            - stops the server if running"
  echo "    restart         - stops the server if runing, and restarts it"
  echo "    open_permission - open firewall port for 51080&51090"
  echo "    help            - This help"
  echo ""
}

detect_platform() {
  case $(uname -s) in
  Darwin)
    SERVER_PCK='macosx'
    ;;
  Linux)
    SERVER_PCK='linux32'
    arch=$(uname -m)
    if [ "$arch" = "x86_64" ]; then
      SERVER_PCK='linux64'
    fi
    ;;
  FreeBSD)
    SERVER_PCK='freebsd32'
    arch=$(uname -m)
    if [ "$arch" = "amd64" ]; then
      SERVER_PCK='freebsd64'
    fi
    ;;
  *)
    echo "Please Select the server Platform: "
    echo "1) macOS"
    echo "2) Linux (32bit)"
    echo "3) Linux (64bit)"
    echo "4) FreeBSD (32bit)"
    echo "5) FreeBSDD (64bit)"

    read platform
    case $platform in
    1) SERVER_PCK='macosx' ;;
    2) SERVER_PCK='linux32' ;;
    3) SERVER_PCK='linux64' ;;
    4) SERVER_PCK='freebsd32' ;;
    5) SERVER_PCK='freebsd64' ;;
    esac
    ;;
  esac

  SERVER_PCK="${SERVER_PCK}_jre"

  echo "Server Platform is $SERVER_PCK"
}

confirm_install() {
  if [ "$INSTALL_DIR" != "" ]; then
    printf "This will install the Speedtest-node server for $SERVER_PCK to folder $INSTALL_DIR. Please confirm(y/n)"
  else
    printf "This will install the Speedtest-node server for $SERVER_PCK to the current folder. Please confirm(y/n)"
  fi
  read response
  if [ "$response" != "y" ] && [ "$response" != "Y" ]; then
    echo "Exiting install"
    exit 1
  fi
}

goto_install_folder() {
  dir_full=$(pwd)
  dir_base=$(basename $dir_full)

  if [ "$INSTALL_DIR" != "" ]; then
    if [ "$dir_base" != "$INSTALL_DIR" ]; then
      mkdir "$INSTALL_DIR"
      scriptname=$(basename $0)
      cp "$scriptname" "$INSTALL_DIR"
    fi

    cd "$INSTALL_DIR"
  fi
}

download_install_pck() {
  pck_file="${LOCAL_PCK}.tar.gz"
  download_url="${NODE_PCK_DOWNLOAD_URL}${LOCAL_PCK}-${SERVER_PCK}.tar.gz"

  curl_path=$(command -v curl)
  wget_path=$(command -v wget)
  fetch_path=$(command -v fetch)

  echo "Start download speedtest-node package..."
  if [ -n "$curl_path" ]; then
    curl -o $pck_file $download_url
  elif [ -n "$wget_path" ]; then
    wget -O $pck_file $download_url
  elif [ -n "$fetch_path" ]; then
    fetch_path -o $pck_file $download_url
  else
    echo "This script requires CURL or WGET or FETCH"
    exit 1
  fi

  if [ -f $pck_file ]; then
    echo "unzip download file"
    tar -xzvf "$pck_file"
    rm -f "$pck_file"
  else
    echo "Error download speedtest-node package."
    exit 1
  fi
}

goto_node_folder() {
  if [ -d "$LOCAL_PCK" ]; then
    cd "$LOCAL_PCK"
  else
    echo "Error !! - no $LOCAL_PCK folder"
    exit 1
  fi
}

start_server() {
  goto_node_folder

  if [ -d "info" ]; then
    rm -rf info
  fi

  $JAVA_ENV -jar speedtest-node.jar &
  echo -e "${GREEN}start node success!${NC}"

  $JAVA_ENV -cp speedtest-node.jar cn.speedtest.Daemon &
  echo -e "${GREEN}start daemon success!${NC}"
}

stop_server() {
  goto_node_folder

  declare -A process_map=(["main"]="0" ["daemon"]="0")
  for line in $(cat "./info/process_info"); do
    line_array=(${line//:/ })
    process_map[${line_array[0]}]=${line_array[1]}
  done

  # shellcheck disable=SC2068
  for pn in ${!process_map[@]}; do
    echo "stop ${pn} - ${process_map[$pn]}"
    kill -9 ${process_map[$pn]}
  done

  echo -e "${GREEN}speedtest-node server stop.${NC}"
}

restart() {
  stop_server
  start_server
}

open_permission() {
  $(command -v firewall-cmd)
  echo `firewall-cmd --state`
  firewall-cmd --state
  firewall-cmd --permanent --zone=public --add-port=51080/tcp
  firewall-cmd --permanent --zone=public --add-port=51090/tcp
  firewall-cmd --reload
}

#################Main#################

action=help
while [ "$1" != "" ]; do
  case $1 in
  install)
    action=install
    ;;
  stop)
    action=stop
    ;;
  start)
    action=start
    ;;
  restart)
    action=restart
    ;;
  help)
    action=help
    ;;
  open_permission)
    action=open_permission
    ;;
  -O | --output)
    shift
    INSTALL_DIR=$1
    ;;
  *)
    display_usage
    exit 1
    ;;
  esac
  shift
done

if [ "$action" = "install" ]; then
  detect_platform
  confirm_install
  goto_install_folder
  download_install_pck
  start_server
  echo -e "${GREEN}finish install.${NC}"
fi

if [ "$action" = "help" ]; then
  display_usage
fi

if [ "$action" = "start" ]; then
  start_server
fi

if [ "$action" = "stop" ]; then
  stop_server
fi

if [ "$action" = "open_permission" ]; then
  open_permission
fi
