#!/usr/bin/env bash

set -e +o pipefail

show_help() {
cat << EOF

      Alibaba Cloud Command Line Interface Installer

    -h          Display this help and exit

    -f          Force install, skip conflict detection

    -V VERSION  Custom CLI version. Default is 'latest'

EOF
}

abort() {
  printf "%s\n" "$@" >&2
  exit 1
}

cleanup() {
  if [[ -n "${WORK_DIR-}" ]] && [[ -d "$WORK_DIR" ]]; then
    rm -rf "$WORK_DIR"
  fi
}
trap cleanup EXIT

# First check OS.
OS="$(uname)"
if [[ "${OS}" == "Linux" ]]
then
  CLI_ON_LINUX=1
elif [[ "${OS}" == "Darwin" ]]
then
  CLI_ON_MACOS=1
else
  abort "Currently is only supported on macOS and Linux."
fi

VERSION="latest"
FORCE=0

if [ $# != 0 ];
then
  while getopts "hfV:-" o
  do
    case "$o" in
      "h")
        show_help
        exit 0;
        ;;
      "f")
        FORCE=1
        ;;
      "V")
        VERSION="$OPTARG"
        ;;
      *)
        echo -e "Unexpected flag not supported"
        exit 1
        ;;
    esac
  done
fi

echo -e "
..............888888888888888888888 ........=8888888888888888888D=..............
...........88888888888888888888888 ..........D8888888888888888888888I...........
.........,8888888888888ZI: ...........................=Z88D8888888888D..........
.........+88888888 ..........................................88888888D..........
.........+88888888 .......Welcome to use Alibaba Cloud.......O8888888D..........
.........+88888888 ............. ************* ..............O8888888D..........
.........+88888888 .... Command Line Interface(Reloaded) ....O8888888D..........
.........+88888888...........................................88888888D..........
..........D888888888888DO+. ..........................?ND888888888888D..........
...........O8888888888888888888888...........D8888888888888888888888=...........
............ .:D8888888888888888888.........78888888888888888888O ..............
"

WORK_DIR=$(mktemp -d)
INSTALL_PATH="/usr/local/bin/aliyun"
CDN_BASE="https://aliyuncli.alicdn.com"

# Detect existing installation
EXISTING_ALIYUN_PATH=""
EXISTING_VERSION=""
IS_UPDATE=0
if command -v aliyun >/dev/null 2>&1; then
  EXISTING_ALIYUN_PATH=$(command -v aliyun)
  EXISTING_VERSION=$(aliyun version 2>/dev/null || echo "unknown")
  IS_UPDATE=1
  echo "Found existing Alibaba Cloud CLI:"
  echo "  Path:    $EXISTING_ALIYUN_PATH"
  echo "  Version: $EXISTING_VERSION"
  echo ""
fi

# --- macOS ---
if [[ -n "${CLI_ON_MACOS-}" ]]
then
  if [[ -n "$EXISTING_ALIYUN_PATH" ]] && [[ $FORCE -eq 0 ]]; then
    if [[ "$EXISTING_ALIYUN_PATH" == "$INSTALL_PATH" ]]; then
      # Same path — treat as update, check if Homebrew-managed
      IS_BREW_INSTALLED=0
      if [[ -L "$EXISTING_ALIYUN_PATH" ]] && [[ "$(readlink "$EXISTING_ALIYUN_PATH" 2>/dev/null)" == *"Cellar"* ]]; then
        IS_BREW_INSTALLED=1
      elif command -v brew >/dev/null 2>&1 && brew list aliyun-cli >/dev/null 2>&1; then
        IS_BREW_INSTALLED=1
      fi

      if [[ $IS_BREW_INSTALLED -eq 1 ]]; then
        abort "Error: The existing aliyun CLI at $EXISTING_ALIYUN_PATH was installed via Homebrew." \
              "" \
              "To avoid conflicts, please remove it first:" \
              "  brew uninstall aliyun-cli" \
              "" \
              "Then re-run this script. Or use -f to force install."
      fi
    elif [[ "$EXISTING_ALIYUN_PATH" == "/opt/homebrew/bin/aliyun" ]]; then
      # Homebrew at /opt/homebrew, install target is /usr/local/bin — will not take precedence
      abort "Error: Found Homebrew-installed aliyun CLI at $EXISTING_ALIYUN_PATH." \
            "Installing to $INSTALL_PATH would not take precedence over the Homebrew version." \
            "" \
            "To resolve this, choose one of the following:" \
            "  1. Uninstall the Homebrew version:  brew uninstall aliyun-cli" \
            "  2. Ensure /usr/local/bin comes before /opt/homebrew/bin in your PATH" \
            "" \
            "Then re-run this script. Or use -f to force install."
    else
      # Existing aliyun at an unexpected path
      abort "Error: Found existing aliyun CLI at $EXISTING_ALIYUN_PATH (expected $INSTALL_PATH)." \
            "Installing to $INSTALL_PATH may not take effect because the existing version takes precedence in PATH." \
            "" \
            "To resolve this, choose one of the following:" \
            "  1. Remove or rename the existing binary: rm $EXISTING_ALIYUN_PATH" \
            "  2. Ensure /usr/local/bin comes before $(dirname "$EXISTING_ALIYUN_PATH") in your PATH" \
            "" \
            "Then re-run this script. Or use -f to force install."
    fi
  fi

  DOWNLOAD_FILE="aliyun-cli-macosx-${VERSION}-universal.tgz"
  curl -o "${WORK_DIR}/${DOWNLOAD_FILE}" -fsSL "${CDN_BASE}/${DOWNLOAD_FILE}"
  tar zxf "${WORK_DIR}/${DOWNLOAD_FILE}" -C "$WORK_DIR"

  if ! mv "${WORK_DIR}/aliyun" "$INSTALL_PATH" 2>/dev/null; then
    echo "Permission denied. Retrying with sudo..."
    sudo mv "${WORK_DIR}/aliyun" "$INSTALL_PATH" || abort "Failed to install to $INSTALL_PATH. Please check your permissions."
  fi
  chmod +x "$INSTALL_PATH" 2>/dev/null || sudo chmod +x "$INSTALL_PATH" || abort "Failed to set executable permission on $INSTALL_PATH."
fi

# --- Linux ---
if [[ -n "${CLI_ON_LINUX-}" ]]
then
  if [[ -n "$EXISTING_ALIYUN_PATH" ]] && [[ $FORCE -eq 0 ]]; then
    if [[ "$EXISTING_ALIYUN_PATH" == "$INSTALL_PATH" ]]; then
      # Same path — treat as update, check if package-manager-managed
      IS_PACKAGE_MANAGER_INSTALLED=0
      PACKAGE_MANAGER=""
      if command -v dpkg >/dev/null 2>&1 && dpkg -l | grep -q aliyun-cli; then
        IS_PACKAGE_MANAGER_INSTALLED=1
        PACKAGE_MANAGER="apt/dpkg"
      elif command -v rpm >/dev/null 2>&1 && rpm -qa | grep -q aliyun-cli; then
        IS_PACKAGE_MANAGER_INSTALLED=1
        PACKAGE_MANAGER="rpm/yum/dnf"
      elif command -v pacman >/dev/null 2>&1 && pacman -Q aliyun-cli >/dev/null 2>&1; then
        IS_PACKAGE_MANAGER_INSTALLED=1
        PACKAGE_MANAGER="pacman"
      fi

      if [[ $IS_PACKAGE_MANAGER_INSTALLED -eq 1 ]]; then
        abort "Error: The existing aliyun CLI at $EXISTING_ALIYUN_PATH was installed via $PACKAGE_MANAGER." \
              "" \
              "To avoid conflicts, please remove it first using your package manager." \
              "" \
              "Then re-run this script. Or use -f to force install."
      fi
    else
      # Existing aliyun at a different path
      abort "Error: Found existing aliyun CLI at $EXISTING_ALIYUN_PATH (expected $INSTALL_PATH)." \
            "Installing to $INSTALL_PATH may not take effect because the existing version takes precedence in PATH." \
            "" \
            "To resolve this, choose one of the following:" \
            "  1. Remove or rename the existing binary: sudo rm $EXISTING_ALIYUN_PATH" \
            "  2. Ensure /usr/local/bin comes before $(dirname "$EXISTING_ALIYUN_PATH") in your PATH" \
            "" \
            "Then re-run this script. Or use -f to force install."
    fi
  fi

  UNAME_MACHINE="$(/usr/bin/uname -m)"
  if [[ "${UNAME_MACHINE}" == "arm64" || "${UNAME_MACHINE}" == "aarch64" ]]; then
    DOWNLOAD_FILE="aliyun-cli-linux-${VERSION}-arm64.tgz"
  else
    DOWNLOAD_FILE="aliyun-cli-linux-${VERSION}-amd64.tgz"
  fi

  curl -o "${WORK_DIR}/${DOWNLOAD_FILE}" -fsSL "${CDN_BASE}/${DOWNLOAD_FILE}"
  tar zxf "${WORK_DIR}/${DOWNLOAD_FILE}" -C "$WORK_DIR"

  if ! mv "${WORK_DIR}/aliyun" "$INSTALL_PATH" 2>/dev/null; then
    echo "Permission denied. Retrying with sudo..."
    sudo mv "${WORK_DIR}/aliyun" "$INSTALL_PATH" || abort "Failed to install to $INSTALL_PATH. Please check your permissions."
  fi
  chmod +x "$INSTALL_PATH" 2>/dev/null || sudo chmod +x "$INSTALL_PATH" || abort "Failed to set executable permission on $INSTALL_PATH."
fi

# --- Post-install verification ---
echo ""
if [[ $IS_UPDATE -eq 1 ]]; then
  echo "Update completed successfully!"
else
  echo "Installation completed successfully!"
fi
echo "  Path: $INSTALL_PATH"

if command -v aliyun >/dev/null 2>&1; then
  NEW_VERSION=$(aliyun version 2>/dev/null || echo "unknown")
  echo "  Version: $NEW_VERSION"

  if [[ $IS_UPDATE -eq 1 ]] && [[ "$EXISTING_VERSION" != "unknown" ]] && [[ "$NEW_VERSION" != "unknown" ]] && [[ "$EXISTING_VERSION" != "$NEW_VERSION" ]]; then
    echo "  (updated from $EXISTING_VERSION)"
  fi
fi
