#!/usr/bin/env /usr/bin/bash
# shellcheck shell=bash
# x2openEuler deployment script
# Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.

# https://www.gnu.org/software/bash/manual/bash.html#The-Set-Builtin
set -euo pipefail

# Create a temporary resource directory.
# https://www.gnu.org/software/coreutils/manual/coreutils.html#mktemp-invocation
TEMP_DIR=$(mktemp -d)

# Clear temporary cache resources.
cleanup() {
  /usr/bin/rm -rf "${TEMP_DIR}"
}

# Capture (SIGINT EXIT) signals and execute cleanup() function.
# https://www.gnu.org/software/bash/manual/bash.html#index-trap
trap cleanup SIGINT EXIT

# LOG handler.
_log() {
  local LEVEL_NAME="$1"
  # https://www.gnu.org/software/bash/manual/bash.html#index-shift
  shift
  local MESSAGE=$*
  local TIMESTAMP
  # https://www.gnu.org/software/coreutils/manual/coreutils.html#date-invocation
  TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S.%3N")
  echo -e "[${TIMESTAMP}] [${LEVEL_NAME}] ${MESSAGE}"
}

# https://en.wikipedia.org/wiki/ANSI_escape_code
# https://misc.flogisoft.com/bash/tip_colors_and_formatting
COLOR_LOG_DEBUG="\033[34m"    # Blue
COLOR_LOG_INFO="\033[32m"     # Green
COLOR_LOG_WARNING="\033[33m"  # Yellow
COLOR_LOG_ERROR="\033[31m"    # Red
COLOR_LOG_CRITICAL="\033[35m" # Purple
COLOR_LOG_RESET="\033[0m"     # Reset color

log_debug() {
  _log "${COLOR_LOG_DEBUG}DEBUG${COLOR_LOG_RESET}" "${COLOR_LOG_DEBUG}$*${COLOR_LOG_RESET}"
}

log_info() {
  _log "${COLOR_LOG_INFO}INFO${COLOR_LOG_RESET}" "${COLOR_LOG_INFO}$*${COLOR_LOG_RESET}"
}

log_warn() {
  _log "${COLOR_LOG_WARNING}WARNING${COLOR_LOG_RESET}" "${COLOR_LOG_WARNING}$*${COLOR_LOG_RESET}" >&2
}

log_error() {
  _log "${COLOR_LOG_ERROR}ERROT${COLOR_LOG_RESET}" "${COLOR_LOG_ERROR}$*${COLOR_LOG_RESET}" >&2
  # https://www.gnu.org/software/bash/manual/bash.html#Exit-Status
  exit 1
}

log_critical() {
  _log "${COLOR_LOG_CRITICAL}CRITICAL${COLOR_LOG_RESET}" "${COLOR_LOG_CRITICAL}$*${COLOR_LOG_RESET}" >&2
  # https://www.gnu.org/software/bash/manual/bash.html#Exit-Status
  exit 2
}

# Check if the OS is linux.
[[ "$(uname -s)" = "Linux" ]] || log_critical 'This script is intended to run on Linux only.'

# Get machine hardware name.
ARCH=$(uname -m)
case "${ARCH}" in
x86_64)
  ARCH="x86_64"
  ;;
aarch64 | arm64)
  ARCH="aarch64"
  ;;
*)
  log_warn "Unknown architecture: ${ARCH}"
  ARCH="noarch"
  ;;
esac

# Command line availability check.
available() {
  command -v "$1" >/dev/null 2>&1
}

# Check whether the command line necessary for subsequent script execution exists.

# Get OS package management tools.
_os_release_check() {
  # Distinguish system type by (dpkg/rpm)
  local OS_PKG_TOOL="$1"
  local OS_RELEASE="/etc/os-release"
  local DEBIAN_VERSION="/etc/debian_version"
  local REDHAT_RELEASE="/etc/redhat-release"
  local KYLIN_RELEASE="/etc/kylin-release"
  local OPENEULER_RELEASE="/etc/openEuler-release"
  [ -f "${OS_RELEASE}" ] || log_critical "'${OS_RELEASE}' file not found, cannot continue execution."
  # shellcheck source=/dev/null
  source "${OS_RELEASE}"
  if [ -f "${DEBIAN_VERSION}" ] || grep -q "ID_LIKE=debian" "${OS_RELEASE}" && available dpkg && [[ "dpkg" = "${OS_PKG_TOOL}" ]]; then
    log_info "The current operating system is: ${PRETTY_NAME}"
    return 0
  elif [ -f "${REDHAT_RELEASE}" ] || grep -q 'ID_LIKE="rhel fedora"' "${OS_RELEASE}" && available rpm && [[ "rpm" = "${OS_PKG_TOOL}" ]]; then
    log_info "The current operating system is: ${PRETTY_NAME}"
    return 0
  elif [[ -f "${KYLIN_RELEASE}" && "kylin" = "${ID}" ]] || [[ -f "${OPENEULER_RELEASE}" && "openEuler" = "${ID}" ]] || [[ "uos" = "${ID}" ]] && available rpm && [[ "rpm" = "${OS_PKG_TOOL}" ]]; then
    log_info "The current operating system is: ${PRETTY_NAME}"
    return 0
  else
    log_warn "Unknown system type."
    return 1
  fi
}

get_pmt() {
  PACKAGE_MANAGE_TOOL=
  if _os_release_check rpm; then
    for PACKAGE_MANAGE_TOOL in dnf yum; do
      if available "${PACKAGE_MANAGE_TOOL}"; then
        log_info "Package installation will be performed using \"${PACKAGE_MANAGE_TOOL}\""
        break
      fi
    done
  fi
  [ $PACKAGE_MANAGE_TOOL ] || log_error "No available package management tool found."
}

# Get SUDO command line
get_sudo() {
  SUDO=
  if [[ "$(whoami)" != "root" ]] && [ "$(id -u)" -ne 0 ]; then
    log_info "Currently executing commands as the regular user $(whoami)."
    available sudo || log_error "sudo command not found, subsequent commands cannot be executed using sudo as the regular user $(whoami)."
    sudo -l >/dev/null 2>&1 || log_error "Sorry, regular user $(whoami) may not run sudo on $(whoami)."
    log_warn "When executing subsequent commands as the regular user $(whoami), please enter your sudo password as prompted."
    SUDO=sudo
  else
    log_info "Currently executing commands as root."
  fi
}

# Help information
usage() {
  printf "%s" "
===========================================================================
Installation and Uninstallation Tool for Application x2openEuler.
---------------------------------------------------------------------------
Usage: deploy-x2openEuler [options] COMMAND
---------------------------------------------------------------------------
List of Main Commands:
install                   install a package or packages on your system
uninstall                 uninstall a package or packages from your system
---------------------------------------------------------------------------
Optional arguments:
  -p, --path              rpm package file path
  -h, --help              Show command help
  -v, --version           Show version information
===========================================================================
"
  exit 1
}

# Get Args
get_args() {
  while [[ "${1:-}" ]]; do
    case "${1}" in
    "install" | "uninstall")
      main_command="${1:-}"
      ;;
    "-p" | "--path")
      optional_path="${2:-}"
      if [ "${optional_path}" ] && [ -n "${optional_path}" ] && [ "${optional_path}" != "install" ] && [ "${optional_path}" != "uninstall" ]; then
        shift
      else
        optional_path=""
      fi
      ;;
    "-h" | "--help")
      usage
      ;;
    "-v" | "--version")
      echo -e "\033[38;2;233;115;12mdeploy-x2openEuler version is 0.0.1\033[0m"
      exit 0
      ;;
    *)
      log_warn "Unknown parameter, please refer to the help information."
      usage
      ;;
    esac
    shift
  done
}

get_basic_commands() {
  if ! [ "$1" ] || [ -z "$1" ]; then
    log_warn "The 'install' or 'uninstall' parameter must be specified."
    usage
  fi
  get_pmt
  if [[ "yum" = "${PACKAGE_MANAGE_TOOL}" && "install" = "$1" ]]; then
    main_command='localinstall'
  fi
}

get_pkg_file() {
  if ! [ "$1" ] || [ -z "$1" ]; then
    log_warn "The '-p' or '--path' parameter must be specified."
    usage
  fi
  local pkg_file_abs_path
  pkg_file_abs_path=$(realpath "$1")
  if [ -f "${pkg_file_abs_path}" ] && [ "application/x-rpm" = "$(file -b --mime-type "${pkg_file_abs_path}")" ]; then
    pkg_file_name="$(basename "${pkg_file_abs_path}")"
    [[ "${pkg_file_name}" =~ x2openEuler-upgrade-[0-9]+\.[0-9]+\.[0-9]+-[0-9]{8}\.${ARCH}\.rpm ]] || log_error "The RPM installation package is not the expected architecture. The current system architecture is: ${ARCH}."
    local pkg_file_name_date_str
    pkg_file_name_date_str="$(echo "${pkg_file_name}" | grep -oE '[0-9]{8}')"
    (date -d "${pkg_file_name_date_str}" "+%Y%m%d" >/dev/null 2>&1 && [ "$(date -d "${pkg_file_name_date_str}" "+%Y%m%d")" = "${pkg_file_name_date_str}" ]) || log_error "RPM installation package with illegal file name."
    optional_path="${pkg_file_abs_path}"
  else
    log_error "'$1' is not a valid rpm installation file."
  fi
}

# Check if it is installed
_is_installd() {
  if rpm -q "${pkg_file_name%.*}" >/dev/null 2>&1 && available x2openEuler-migrate; then
    return 0
  else
    return 1
  fi
}

execute() {
  get_sudo
  local rpm_pkg_name
  rpm_pkg_name="${pkg_file_name%.*}"
  case "${main_command}" in
  "install" | "localinstall")
    log_info "Start the Installation."
    ! _is_installd || log_error "Application ${rpm_pkg_name} has been installed."
    if $SUDO $PACKAGE_MANAGE_TOOL -y "$main_command" "$optional_path"; then
      _is_installd || log_error "Application ${rpm_pkg_name} failed to install."
      log_info "Installation completed."
      return 0
    else
      log_error "Installation failed"
    fi
    ;;
  "uninstall")
    log_info "Start the Uninstallation."
      _is_installd || log_error "Application ${rpm_pkg_name} has been uninstall."
    if $SUDO $PACKAGE_MANAGE_TOOL -y remove "${rpm_pkg_name}"; then
      ! _is_installd || log_error "Application ${rpm_pkg_name} failed to uninstall."
      log_info "Uninstallation completed."
      return 0
    else
      log_error "Uninstallation failed"
    fi
    ;;
  esac
}

main() {
  get_args "$@"
  get_basic_commands "${main_command:-}"
  get_pkg_file "${optional_path}"
  execute
}

main "$@"
