#!/usr/bin/env sh
set -eu

base_url="${FORKR_INSTALL_BASE_URL:-https://github.com/forkr/forkr/releases/latest/download}"
bin_dir="${FORKR_INSTALL_DIR:-$HOME/.local/bin}"
tmp_dir="${TMPDIR:-/tmp}/forkr-install-$$"

need() {
  command -v "$1" >/dev/null 2>&1 || {
    echo "missing required command: $1" >&2
    exit 1
  }
}

detect_target() {
  os="$(uname -s | tr '[:upper:]' '[:lower:]')"
  arch="$(uname -m)"
  case "$os:$arch" in
    linux:x86_64|linux:amd64) echo "x86_64-unknown-linux-gnu" ;;
    linux:aarch64|linux:arm64) echo "aarch64-unknown-linux-gnu" ;;
    darwin:x86_64|darwin:amd64) echo "x86_64-apple-darwin" ;;
    darwin:aarch64|darwin:arm64) echo "aarch64-apple-darwin" ;;
    *)
      echo "unsupported platform: $os/$arch" >&2
      exit 1
      ;;
  esac
}

need curl
need tar

target="$(detect_target)"
archive="4kr-${target}.tar.gz"
url="${base_url%/}/${archive}"

rm -rf "$tmp_dir"
mkdir -p "$tmp_dir" "$bin_dir"
trap 'rm -rf "$tmp_dir"' EXIT INT TERM

echo "Downloading $url"
curl -fsSL "$url" -o "$tmp_dir/$archive"
tar -xzf "$tmp_dir/$archive" -C "$tmp_dir"

if [ ! -f "$tmp_dir/4kr" ]; then
  echo "archive did not contain 4kr" >&2
  exit 1
fi

chmod 0755 "$tmp_dir/4kr"
mv "$tmp_dir/4kr" "$bin_dir/4kr"

echo "Installed 4kr to $bin_dir/4kr"
case ":$PATH:" in
  *":$bin_dir:"*) ;;
  *)
    echo "Add this to PATH if needed:"
    echo "  export PATH=\"$bin_dir:\$PATH\""
    ;;
esac
echo "Next:"
echo "  4kr setup ui"
