#!/bin/bash

set -euo pipefail

BASE_URL="http://viking-skills.tos-cn-beijing.volces.com/viking-cli"
BIN_NAME="viking-cli"

usage() {
  cat <<'EOF'
Usage:
  ./install.sh [--bin-dir <dir>] [--prefix <dir>] [--help]

Examples:
  ./install.sh
  ./install.sh --bin-dir "$HOME/.local/bin"
  sudo ./install.sh --prefix /usr/local

Notes:
  - Default install dir: first writable of /usr/local/bin, /opt/homebrew/bin, otherwise ~/.local/bin
  - Downloads from: http://viking-skills.tos-cn-beijing.volces.com/viking-cli/<os>-<arch>/viking-cli[.exe]
EOF
}

bin_dir=""
prefix=""

while [ $# -gt 0 ]; do
  case "$1" in
    --bin-dir)
      bin_dir="${2:-}"
      shift 2
      ;;
    --prefix)
      prefix="${2:-}"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown arg: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if [ -n "$prefix" ] && [ -n "$bin_dir" ]; then
  echo "Only one of --prefix or --bin-dir can be set." >&2
  exit 2
fi

os="$(uname -s)"
arch="$(uname -m)"
platform=""
target_arch=""
exe_ext=""

case "$os" in
  Darwin)
    platform="darwin"
    ;;
  Linux)
    platform="linux"
    ;;
  MINGW*|MSYS*|CYGWIN*)
    platform="windows"
    exe_ext=".exe"
    ;;
  *)
    echo "Unsupported operating system: $os" >&2
    exit 1
    ;;
esac

case "$arch" in
  x86_64|amd64)
    target_arch="amd64"
    ;;
  arm64|aarch64)
    target_arch="arm64"
    ;;
  *)
    echo "Unsupported architecture: $arch" >&2
    exit 1
    ;;
esac

if [ -n "$prefix" ]; then
  bin_dir="${prefix%/}/bin"
fi

pick_default_bin_dir() {
  local d=""

  for d in "/usr/local/bin" "/opt/homebrew/bin"; do
    if [ -d "$d" ] && [ -w "$d" ]; then
      echo "$d"
      return 0
    fi
  done

  echo "$HOME/.local/bin"
}

if [ -z "$bin_dir" ]; then
  bin_dir="$(pick_default_bin_dir)"
fi

mkdir -p "$bin_dir"

target="${platform}-${target_arch}"
url="${BASE_URL}/${target}/${BIN_NAME}${exe_ext}"

tmp="$(mktemp)"
cleanup() {
  rm -f "$tmp"
}
trap cleanup EXIT

echo "Downloading: $url" >&2

if command -v curl >/dev/null 2>&1; then
  curl -fL --retry 3 --connect-timeout 10 --max-time 300 -o "$tmp" "$url"
elif command -v wget >/dev/null 2>&1; then
  wget -O "$tmp" "$url"
else
  echo "Neither curl nor wget found. Please install one of them." >&2
  exit 1
fi

chmod +x "$tmp"
install_path="${bin_dir%/}/${BIN_NAME}${exe_ext}"
mv -f "$tmp" "$install_path"

echo "Installed: $install_path" >&2

case ":$PATH:" in
  *":${bin_dir%/}:"*)
    ;;
  *)
    echo "Warning: ${bin_dir%/} is not in PATH." >&2
    echo "Add it to PATH, e.g.:" >&2
    echo "  export PATH=\"${bin_dir%/}:\$PATH\"" >&2
    ;;
esac

echo "Done. Try: ${BIN_NAME} version" >&2

