#!/usr/bin/env bash

set -euo pipefail

readonly DEFAULT_SERVER_BASE_URL="https://tiiny-cli.tiiny.cloud"
readonly DEFAULT_LAUNCHER_VERSION="v1"
readonly DATA_DIR="${HOME}/.local/tiiny"
readonly BIN_DIR="${DATA_DIR}/bin"
readonly CONFIG_PATH="${DATA_DIR}/config.json"
readonly LEGACY_CONFIG_DIR="${HOME}/.tiiny"
readonly LEGACY_CONFIG_PATH="${HOME}/.tiiny/config.json"
readonly LAUNCHER_NAME="tiiny"

usage() {
  cat <<'EOF'
Usage: install-linux.sh [upgrade] [-y|--yes]

Commands:
  upgrade              Download the latest CLI binary through the launcher.

Options:
  -y, --yes            Confirm the upgrade without prompting.
  -h, --help           Show this help message.

Environment:
  TIINY_LAUNCHER_URL  Override the launcher download URL.
EOF
}

log() {
  printf '[tiiny installer] %s\n' "$*"
}

fail() {
  printf '[tiiny installer] error: %s\n' "$*" >&2
  exit 1
}

require_command() {
  command -v "$1" >/dev/null 2>&1 || fail "$1 is required"
}

append_path_entry() {
  local rc_file="$1"
  local path_line='export PATH="$HOME/.local/tiiny/bin:$PATH"'

  touch "$rc_file"
  if ! grep -Fqx "$path_line" "$rc_file" 2>/dev/null; then
    printf '\n%s\n' "$path_line" >>"$rc_file"
    log "added ${BIN_DIR} to PATH in ${rc_file}"
  fi
}

migrate_config() {
  if [[ ! -f "$LEGACY_CONFIG_PATH" || -e "$CONFIG_PATH" ]]; then
    return
  fi

  mkdir -p "$DATA_DIR"
  mv -- "$LEGACY_CONFIG_PATH" "$CONFIG_PATH"
  chmod 0600 "$CONFIG_PATH"
  log "migrated config to ${CONFIG_PATH}"
}

remove_legacy_config_dir() {
  [[ -d "$LEGACY_CONFIG_DIR" ]] || return 0
  rm -rf -- "$LEGACY_CONFIG_DIR"
  log "removed legacy data directory ${LEGACY_CONFIG_DIR}"
}

remove_legacy_binaries() {
  local legacy_dir path
  local -a legacy_dirs=(
    "${HOME}/.local/bin"
    "/usr/local/bin"
  )

  for legacy_dir in "${legacy_dirs[@]}"; do
    [[ -d "$legacy_dir" ]] || continue

    while IFS= read -r -d '' path; do
      if [[ -w "$legacy_dir" ]]; then
        rm -f -- "$path"
      elif command -v sudo >/dev/null 2>&1; then
        sudo rm -f -- "$path"
      else
        fail "cannot remove legacy Tiiny binary ${path}; sudo is required"
      fi
      log "removed legacy binary ${path}"
    done < <(
      find "$legacy_dir" -maxdepth 1 -mindepth 1 \
        \( -type f -o -type l \) \
        -iname '*tiiny*' \
        -print0
    )
  done
}

remove_local_binaries() {
  local path

  [[ -d "$BIN_DIR" ]] || return 0
  for path in "$BIN_DIR"/tiiny*; do
    [[ -f "$path" || -L "$path" ]] || continue
    rm -f -- "$path"
    log "removed local Tiiny binary ${path}"
  done
}

sync_file() {
  local file_path="$1"

  if command -v sync >/dev/null 2>&1; then
    sync -f "$file_path" 2>/dev/null || sync
  fi
}

install_launcher() {
  local server_base_url launcher_url launcher_path
  local -a curl_args

  server_base_url="${TIINY_SERVER_BASE_URL:-$DEFAULT_SERVER_BASE_URL}"
  server_base_url="${server_base_url%/}"
  launcher_url="${TIINY_LAUNCHER_URL:-${server_base_url}/tiiny-launcher-linux-${LAUNCHER_ARCH}-${DEFAULT_LAUNCHER_VERSION}}"
  launcher_path="${BIN_DIR}/${LAUNCHER_NAME}"

  mkdir -p "$BIN_DIR"
  log "downloading launcher from ${launcher_url}"
  curl_args=(
    --fail
    --silent
    --show-error
    --location
    --retry 3
    --connect-timeout 10
  )
  curl "${curl_args[@]}" --output "$launcher_path" "$launcher_url" ||
    fail "launcher download failed: ${launcher_url}"

  [[ -s "$launcher_path" ]] || fail "downloaded launcher is empty"
  chmod 0755 "$launcher_path"
  sync_file "$launcher_path"
  log "installed launcher at ${launcher_path}"
}

start_launcher() {
  local launcher_path="${BIN_DIR}/${LAUNCHER_NAME}"
  local -a launcher_args=(cli upgrade)

  export PATH="${BIN_DIR}:${PATH}"

  if [[ "$ACTION" == "install" || "$ASSUME_YES" == "1" ]]; then
    launcher_args+=(--yes)
  fi
  exec "$launcher_path" "${launcher_args[@]}"
}

[[ "$(uname -s)" == "Linux" ]] || fail "this installer only supports Linux"
case "$(uname -m)" in
  x86_64 | amd64)
    ARCH="amd64"
    LAUNCHER_ARCH="amd64"
    ;;
  aarch64 | arm64)
    ARCH="arm64"
    LAUNCHER_ARCH="arm64"
    ;;
  *) fail "unsupported architecture: $(uname -m)" ;;
esac

require_command curl
require_command grep

ACTION="install"
ASSUME_YES="0"
while [[ $# -gt 0 ]]; do
  case "$1" in
    upgrade)
      [[ "$ACTION" == "install" ]] || fail "upgrade specified more than once"
      ACTION="upgrade"
      shift
      ;;
    -y | --yes)
      ASSUME_YES="1"
      shift
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    *)
      fail "unknown argument: $1"
      ;;
  esac
done

migrate_config
remove_legacy_config_dir
remove_legacy_binaries
remove_local_binaries
install_launcher

append_path_entry "${HOME}/.profile"
if [[ -f "${HOME}/.bashrc" ]]; then
  append_path_entry "${HOME}/.bashrc"
fi

echo "Restart your shell or run 'source ~/.profile' to use it"

start_launcher
