#!/bin/sh
set -eu

BASE_URL="${RETPROXY_DOWNLOAD_BASE:-https://tunnel.retp.net/downloads}"
INSTALL_DIR="${RETPROXY_INSTALL_DIR:-$HOME/.local/bin}"

detect_arch() {
  os="$(uname -s | tr '[:upper:]' '[:lower:]')"
  arch="$(uname -m)"

  case "$os" in
    linux) goos="linux" ;;
    darwin) goos="darwin" ;;
    *)
      echo "Unsupported OS: $os" >&2
      exit 1
      ;;
  esac

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

  echo "${goos}-${goarch}"
}

ensure_dir_in_path() {
  target_dir=$1
  case ":$PATH:" in
    *":$target_dir:"*) return 0 ;;
  esac

  shell_name="$(basename "${SHELL:-sh}")"
  profile="$HOME/.profile"
  case "$shell_name" in
    zsh) profile="$HOME/.zshrc" ;;
    bash) profile="$HOME/.bashrc" ;;
  esac

  mkdir -p "$(dirname "$profile")"
  line="export PATH=\"$target_dir:\$PATH\""
  if [ ! -f "$profile" ] || ! grep -Fq "$line" "$profile"; then
    printf '\n%s\n' "$line" >> "$profile"
  fi

  echo "Added $target_dir to PATH in $profile"
}

target="$(detect_arch)"
binary="retproxy-${target}"
url="${BASE_URL}/${binary}"

install_dir="$INSTALL_DIR"
mkdir -p "$install_dir"
ensure_dir_in_path "$install_dir"
install_cmd="install -m 0755"

tmp_file="$(mktemp)"
trap 'rm -f "$tmp_file"' EXIT

echo "Downloading $url"
curl -fsSL "$url" -o "$tmp_file"
$install_cmd "$tmp_file" "$install_dir/retproxy"

echo "Installed retproxy to $install_dir/retproxy"
echo
echo "Next step:"
echo "  retproxy login"
echo
echo "This install location is user-writable, so retproxy can auto-update itself on future launches."
