#!/usr/bin/env bash

source $DTS_ENV
source $DTS_FUNCS

trap : 2
trap : 3

check_os_version() {
  local os_version=$(grep "VERSION_ID" ${OS_VERSION_FILE} | cut -d "=" -f 2-)
  echo "  DTS version v${os_version}"
}

print_disclaimer() {
echo -e \
"Please note that the report is not anonymous, but we will use it only for\r
backup and future improvement of the Dasharo product. Every log is encrypted\r
and sent over HTTPS, so security is assured.\r
If you still have doubts, you can skip HCL report generation.\r\n
What is inside the HCL report? We gather information about:\r
  - PCI, Super I/O, GPIO, EC, audio, and Intel configuration,\r
  - MSRs, CMOS NVRAM, CPU info, DIMMs, state of touchpad, SMBIOS and ACPI tables,\r
  - Decoded BIOS information, full firmware image backup, kernel dmesg,\r
  - IO ports, input bus types, and topology - including I2C and USB,\r
\r
You can find more info about HCL in docs.dasharo.com/glossary\r"
}

print_banner() {
echo '    ____             __                        ______            __        _____       _ __'
echo '   / __ \____ ______/ /_  ____ __________     /_  __/___  ____  / /____   / ___/__  __(_) /'____
echo '  / / / / __ `/ ___/ __ \/ __ `/ ___/ __ \     / / / __ \/ __ \/ / ___/   \__ \/ / / / / __/ _ \'
echo ' / /_/ / /_/ (__  ) / / / /_/ / /  / /_/ /    / / / /_/ / /_/ / (__  )   ___/ / /_/ / / /_/  __/'
echo '/_____/\__,_/____/_/ /_/\__,_/_/   \____/    /_/  \____/\____/_/____/   /____/\__,_/_/\__/\___/'
echo
}

print_banner

logs_sent=""

while : ; do
  # Each time the main menu is displayed, check for DES credentials and export
  # them, if file exists
  if [ -e "${SE_credential_file}" ]; then
    export CLOUDSEND_LOGS_URL=$(sed -n '1p' < ${SE_credential_file} | tr -d '\n')
    export CLOUDSEND_DOWNLOAD_URL=$(sed -n '2p' < ${SE_credential_file} | tr -d '\n')
    export CLOUDSEND_PASSWORD=$(sed -n '3p' < ${SE_credential_file} | tr -d '\n')
    export USER_DETAILS="$CLOUDSEND_DOWNLOAD_URL:$CLOUDSEND_PASSWORD"
    export DES_IS_LOGGED="true"
  else
    export CLOUDSEND_LOGS_URL="$BASE_CLOUDSEND_LOGS_URL"
    export CLOUDSEND_PASSWORD="$BASE_CLOUDSEND_PASSWORD"
    unset CLOUDSEND_DOWNLOAD_URL
    unset DES_IS_LOGGED
  fi

  echo
  check_os_version
  echo
  echo "  1) Dasharo HCL report - dump hardware information from this device"
  if ! check_if_dasharo; then
    echo "  2) Install Dasharo firmware"
  fi
  if check_if_dasharo; then
    echo "  3) Restore firmware from Dasharo HCL report"
  fi
  if [ -n "${DES_IS_LOGGED}" ]; then
      echo "  4) Edit your DES keys"
      echo "     Logs key    : " ${CLOUDSEND_LOGS_URL}
      echo "     Download key: " ${CLOUDSEND_DOWNLOAD_URL}
      echo "     Password    : " ${CLOUDSEND_PASSWORD}
  else
      echo "  4) Load your DES keys"
  fi
  if check_if_dasharo; then
    echo "  5) Check and apply Dasharo firmware updates"
  fi
  if systemctl is-active sshd.socket > /dev/null 2>&1; then
      echo "  8) Stop SSH server"
  else
      echo "  8) Start SSH server"
  fi
  echo "  9) Shell"
  echo "  10) Power off system"
  echo "  11) Reboot system"
  echo
  read -p "Enter an option: " OPTION
  echo

  case ${OPTION} in
    1)
      print_disclaimer
      read -p "Do you want to support Dasharo development by sending us logs with your hardware configuration? [N/y] "
      case ${REPLY} in
          yes|y|Y|Yes|YES)
          export SEND_LOGS="true"
          echo "Thank you for contributing to the Dasharo development!"
          ;;
          *)
          export SEND_LOGS="false"
          echo "Logs will be saved in root directory."
          echo "Please consider supporting Dasharo by sending the logs next time."
          ;;
      esac
      if [ "${SEND_LOGS}" == "true" ]; then
          # DEPLOY_REPORT variable is used in dasharo-hcl-report to determine
          # which logs should be printed in the terminal, in the future whole
          # dts scripting should get some LOGLEVEL and maybe dumping working
          # logs to file
          export DEPLOY_REPORT="false"
          check_network_connection && ${CMD_DASHARO_HCL_REPORT} && logs_sent="1"
      else
          export DEPLOY_REPORT="false"
          ${CMD_DASHARO_HCL_REPORT}
      fi
      ;;
    2)
      if ! check_if_dasharo; then
        if check_network_connection; then
          echo "Preparing ..."
          if [ -z "${logs_sent}" ]; then
            export SEND_LOGS="true"
            export DEPLOY_REPORT="true"
            if ! ${CMD_DASHARO_HCL_REPORT}; then
              echo -e "Unable to connect to cloud.3mdeb.com for submitting the
                        \rHCL report. Please recheck your internet connection."
            else
              logs_sent="1"
            fi
          fi
        fi
      fi

      if [ -n "${logs_sent}" ]; then
          ${CMD_DASHARO_DEPLOY} install
      fi
      ;;
    3)
      if check_if_dasharo; then
        ${CMD_DASHARO_DEPLOY} restore
      fi
      ;;
    4)
      echo ""
      read -p "Enter logs key:                " 'TMP_CLOUDSEND_LOGS_URL'
      echo ""
      read -p "Enter firmware download key:   " 'TMP_CLOUDSEND_DOWNLOAD_URL'
      echo ""
      read -p "Enter password:                " 'TMP_CLOUDSEND_PASSWORD'

      echo ${TMP_CLOUDSEND_LOGS_URL} > ${SE_credential_file}
      echo ${TMP_CLOUDSEND_DOWNLOAD_URL} >> ${SE_credential_file}
      echo ${TMP_CLOUDSEND_PASSWORD} >> ${SE_credential_file}

      print_green "Dasharo DES credentials have been saved"
      echo "Verifying Dasharo DES credentials..."

      check_se_creds
      if [ $? -eq 0 ]; then
         print_green "Verification of the Dasharo DES was successful. They are valid and will be used."
      else
        echo -e "Something may be wrong with the DES credentials. Please use option 4 to change the DES keys
                  \rand make sure that there is no typo."
        rm ${SE_credential_file}
        export CLOUDSEND_LOGS_URL="$BASE_CLOUDSEND_LOGS_URL"
        export CLOUDSEND_PASSWORD="$BASE_CLOUDSEND_PASSWORD"
        unset CLOUDSEND_DOWNLOAD_URL
        unset DES_IS_LOGGED
      fi
      ;;
    5)
      if check_if_dasharo; then
        # For NovaCustom TGL laptops with Dasharo version lower than 1.3.0,
        # we shall run the ec_transition script instead. See:
        # https://docs.dasharo.com/variants/novacustom_nv4x_tgl/releases/#v130-2022-10-18
        if [ "$BOARD_VENDOR" = "Notebook" ]; then
            case "$SYSTEM_MODEL" in
              "NS50_70MU"|"NV4XMB,ME,MZ")
                compare_versions $DASHARO_VERSION 1.3.0
                if [ $? -eq 1 ]; then
                # For Dasharo version lesser than 1.3.0
                  print_warning "Detected NovaCustom hardware with version < 1.3.0"
                  print_warning "Need to perform EC transition after which the platform will turn off"
                  print_warning "Then, please power it on and proceed with update again"
                  print_warning "EC transition procedure will start in 5 seconds"
                  sleep 5
                  ${CMD_EC_TRANSITION}
                  error_check "Could not perform EC transition"
                fi
                # Continue with regular update process for Dasharo version
                #  greater or equal 1.3.0
                ;;
            esac
        fi

        # Use regular update process for everything else
        ${CMD_DASHARO_DEPLOY} update
      fi
      ;;
    8)
      if systemctl is-active sshd.socket > /dev/null 2>&1; then
        print_green "Turning off the SSH server..."
        systemctl stop sshd.socket
      else
        print_warning "Starting SSH server!"
        print_warning "Now you can log in into the system using root account."
        print_warning "Stopping server will not drop all connected sessions."
        systemctl start sshd.socket
        print_green "Listening on IPs: $(ip -br -f inet a show scope global | grep UP | awk '{ print $3 }' | tr '\n' ' ')"
      fi
      ;;
    9)
      echo "Entering shell, to leave type exit and press Enter or press LCtrl+D"
      echo ""
      ${CMD_SHELL}
      ;;
    10)
      ${CMD_POWEROFF}
      ;;
    11)
      ${CMD_REBOOT}
      ;;
    *)
      ;;
  esac
done
