#!/bin/sh
set -eu

repo_url="${ANUREO_REPO_URL:-https://github.com/hi-youichi/anureo-tunnel.git}"
install_dir="${ANUREO_INSTALL_DIR:-$HOME/.local/bin}"

for command_name in git cmake; do
  if ! command -v "$command_name" >/dev/null 2>&1; then
    echo "Anureo installer: missing required command: $command_name" >&2
    exit 1
  fi
done

work_dir="$(mktemp -d)"
cleanup() { rm -rf "$work_dir"; }
trap cleanup EXIT HUP INT TERM

echo "Cloning Anureo Tunnel…"
git clone --depth 1 "$repo_url" "$work_dir/anureo-tunnel"

echo "Building Anureo CLI…"
cmake -S "$work_dir/anureo-tunnel/cli" -B "$work_dir/build" -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
cmake --build "$work_dir/build" --parallel

mkdir -p "$install_dir"
install -m 755 "$work_dir/build/anureo" "$install_dir/anureo"

echo "Installed Anureo CLI to $install_dir/anureo"
case ":$PATH:" in
  *":$install_dir:"*) ;;
  *) echo "Add $install_dir to PATH, then run: anureo expose --anonymous http://127.0.0.1:8080" ;;
esac
