#!/bin/bash

fn="$0"
[ -L ${fn} ] && fn=$(readlink $fn)
base_dir=$(realpath $(dirname $fn))

USER_NAME=""
[ -f /usr/share/eus-avast/conf/users.txt ] && USER_NAME=$(cat /usr/share/eus-avast/conf/users.txt)
[ -f ${base_dir}/../conf/users.txt ] &&  USER_NAME=$(cat  ${base_dir}/../conf/users.txt)

POSITIONAL_ARGS=()

# Plugin support
PLUGIN_DIR="/usr/share/eus-avast/plugins"
declare -A PLUGIN_COMMANDS
declare -A PLUGIN_DESCRIPTIONS

# Load plugins from the plugin directory
load_plugins() {
    [ ! -d "${PLUGIN_DIR}" ] && return 0

    for plugin_path in "${PLUGIN_DIR}"/*; do
        [ ! -d "${plugin_path}" ] && continue

        local plugin_name=$(basename "${plugin_path}")
        local conf_file="${plugin_path}/plugin.conf"
        local commands_file="${plugin_path}/commands.sh"

        # Skip if required files don't exist
        [ ! -f "${conf_file}" ] || [ ! -f "${commands_file}" ] && continue

        # Source plugin configuration
        unset PLUGIN_NAME PLUGIN_VERSION PLUGIN_DESCRIPTION PLUGIN_COMMANDS
        source "${conf_file}"

        # Validate plugin configuration
        if [ -z "${PLUGIN_NAME}" ] || [ -z "${PLUGIN_COMMANDS}" ]; then
            continue
        fi

        # Source plugin commands
        source "${commands_file}"

        # Register plugin
        PLUGIN_COMMANDS["${PLUGIN_NAME}"]="${PLUGIN_COMMANDS}"
        PLUGIN_DESCRIPTIONS["${PLUGIN_NAME}"]="${PLUGIN_DESCRIPTION}"
    done
}

# Check if a command is a plugin command
is_plugin_command() {
    local cmd="$1"
    [ -n "${PLUGIN_COMMANDS[$cmd]}" ]
}

# Execute plugin command
execute_plugin_command() {
    local plugin_name="$1"
    shift

    # Call plugin's command handler function
    local handler_func="${plugin_name}_command"
    if declare -f "${handler_func}" > /dev/null; then
        ${handler_func} "$@"
    else
        echo "Error: Plugin '${plugin_name}' is not properly configured"
        return 1
    fi
}

# Load all available plugins
load_plugins

show_help_environment()
{
  local envr="main"
  [ -f /usr/share/eus-avast/conf/branch ] && envr=$(cat /usr/share/eus-avast/conf/branch)

  echo "EUS MDM environment usage help"
  echo
  echo "Syntax: em environment [env-name]"
  echo
  echo "[env-name] is name of git branch you would switch to"
  echo
  echo "Current branch is >${envr}<"
}

show_help()
{
   # Display Help
   echo "EUS MDM usage help"
   echo
   echo "Syntax: em [command]"
   echo "options:"
   echo "  logs         show MDM logs from boot time"
   echo "  status       show MDM status"
   echo "  update       exec update for MDM"
   echo "  stop         stop eus-mdm service"
   echo "  start        start eus-mdm service"
   echo "  compliance   show compliance state"
   echo "  boot         boot options, subcommands kernel, show, vars"

   # Show plugin commands if any are loaded
   if [ ${#PLUGIN_COMMANDS[@]} -gt 0 ]; then
       echo
       echo "Plugin commands:"
       for plugin in "${!PLUGIN_COMMANDS[@]}"; do
           local desc="${PLUGIN_DESCRIPTIONS[$plugin]}"
           [ -z "$desc" ] && desc="Plugin: $plugin"
           printf "  %-12s %s\n" "$plugin" "$desc"
       done
   fi
   echo
}

vpn_purge()
{
  verify_string=$(cat /dev/urandom | tr -dc 'a-z' | fold -w 3 | head -n 1)
  read -p "This delete VPN certificate for this machine, if you do know what are you doing write ${verify_string}: " confirm_str
  [ "${confirm_str}" != "${verify_string}" ] && { echo "the strings don't match"; return ;}
  echo "removing certificates and private keys"
  [ -L /home/${USER_NAME}/.cisco/certificates/client/avast.pem ] && rm  /home/${USER_NAME}/.cisco/certificates/client/avast.pem
  [ -L /home/${USER_NAME}/.cisco/certificates/client/private/avast.key ] && rm /home/${USER_NAME}/.cisco/certificates/client/private/avast.key
  [ -f /usr/share/eus-avast/spool/vpn-avast.cer ] && rm /usr/share/eus-avast/spool/vpn-avast.cer
  [ -f /usr/share/eus-avast/spool/vpn-avast.key ] && rm /usr/share/eus-avast/spool/vpn-avast.key
}

vpn_enrol()
{
  if [ -f /usr/share/eus-avast/tooling/enroll-vpn-cert.sh ]; then
    /usr/share/eus-avast/tooling/enroll-vpn-cert.sh ${USER_NAME}
  elif [ -f ${base_dir}/../tooling/enroll-vpn-cert.sh ]; then
    ${base_dir}/../tooling/enroll-vpn-cert.sh ${USER_NAME}
  else
    echo "No script found, please reinstall eus-mdm"
  fi
}

process_env()
{
  local envr="main"
  [ -f /usr/share/eus-avast/conf/branch ] && envr=$(cat /usr/share/eus-avast/conf/branch)

  if [[ $# -eq 0 ]] ; then
      show_help_environment;
      exit 0
  fi
  while [[ $# -gt 0 ]]; do
      case $1 in
        *)
          new_envr=$1
          shift # past argument
          ;;
      esac
  done
  [ ! -z "${new_envr}" ] && echo ${new_envr} | sudo tee /usr/share/eus-avast/conf/branch
}


process_vpn()
{
  if [[ $# -eq 0 ]] ; then
      show_help;
      exit 0
  fi

  while [[ $# -gt 0 ]]; do
      case $1 in
          enroll)
            vpn_enrol;
            shift ;
            ;;
          purge)
            vpn_purge;
            shift
            ;;
          check)
            echo "checking VPN certs"
            ${base_dir}/../tooling/vpn-check.sh
            shift
            ;;
          *)
            show_help
            shift # past argument
            ;;
      esac
  done
}
process_compliance(){
  parm=$#
  if [[ $# -eq 0 ]] ; then
        parm=check
  fi
  while [[ $# -gt 0 ]]; do
        case $1 in
            check)
              echo "checking compliance state"
              sudo ${base_dir}/../tooling/compliance.sh check
              shift
              ;;
            report)
              echo "checking compliance report"
              sudo ${base_dir}/../tooling/compliance.sh report
              shift
              ;;
            report-json)
              sudo ${base_dir}/../tooling/compliance.sh report-json
              shift
              ;;
            sync)
              if [ -f /usr/share/eus-avast/bin/compliant-reports.sh ]
              then
                # remove checksum to force send report
                CHECKSUM_FILE=$(dirname $(mktemp))/report_checksum.txt
                [ -f ${CHECKSUM_FILE} ] && sudo rm -f ${CHECKSUM_FILE}
                # make report
                echo "Generating compliance report start."
                sudo /usr/share/eus-avast/bin/compliant-reports.sh > /dev/null  2>&1
                echo "Generating compliance report done."
              else
                echo "MDM not work correctly, compliance report is missing. Please run `em update` to fix it."
              fi
              shift
              ;;
            *)
              show_help
              shift # past argument
              ;;
        esac
    done
}
process_boot(){
  parm=$#
  if [[ $# -eq 0 ]] ; then
        echo "Boot option subcommands"
        echo " kernel    default kernel forced by MDM"
        echo " show      show all boot options parsed from grub"
        echo " vars      grub variables"
  fi
  while [[ $# -gt 0 ]]; do
        case $1 in
            show)
              echo "list of boot options"
              /usr/bin/cat /boot/grub/grub.cfg /boot/grub/custom.cfg 2>/dev/null | /usr/bin/awk -F\' '$1=="menuentry " || $1=="submenu " {print i++ " : " $2}; /\tmenuentry / {print "" i-1">"j++ " : " $2};'
              shift
              ;;
            vars)
              echo "Show grub environment"
              /usr/bin/grub-editenv list
              shift
              ;;
            kernel)
              echo "Show requested kernel"
              if [ -f /var/eus/mdm/vars/common.yaml ];
              then
                grep KERNEL_VERSION /var/eus/mdm/vars/common.yaml
              else
                echo "File not found, try to fix this with command 'em update'"
              fi
              shift
              ;;
            *)
              show_help
              shift # past argument
              ;;
        esac
    done
}

if [[ $# -eq 0 ]] ; then
    show_help;
    exit 0
fi

while [[ $# -gt 0 ]]; do
  case $1 in
    environment)
      shift # past value
      process_env "$@"
      shift # past value
      ;;
    status)
      systemctl status eus-mdm.service;
      shift # past value
      ;;
    logs)
      journalctl -b -u eus-mdm.service --no-pager
      shift # past value
      ;;
    start)
      sudo systemctl start eus-mdm.service
      sudo systemctl start eus-mdm.timer
      shift ;
      ;;
    stop)
      sudo systemctl stop eus-mdm.timer
      sudo systemctl stop eus-mdm.service
      shift
      ;;
    update)
      sudo /usr/share/eus-avast/tooling/update.sh;
      shift # past argument
      ;;
    vpn)
      shift # past argument
      shift # past argument
      ;;
    boot)
      shift # past argument
      process_boot "$@"
      shift # past argument
      ;;
    compliance)
      shift # past argument
      process_compliance "$@"
      shift # past argument
      ;;
    version)
      if [ -f ${base_dir}/../version ]
      then
        cat ${base_dir}/../version
      else
        echo "unknown"
      fi
      shift # past argument
      ;;
    *)
      # Check if it's a plugin command
      if is_plugin_command "$1"; then
        plugin_cmd="$1"
        shift
        execute_plugin_command "${plugin_cmd}" "$@"
        exit $?
      else
        show_help
        shift # past argument
      fi
      ;;
  esac
done
