#!/bin/sh
set -eu

require_command() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Missing required command: $1" >&2
    exit 1
  fi
}

shell_base_url='https://www.gitoku.live'
legacy_install_path="$HOME/.local/bin/rgh"
install_dir="${RGH_INSTALL_DIR:-$HOME/.local/bin}"
setup_mode=0

case "${1:-}" in
  setup)
    setup_mode=1
    ;;
esac

case "${RGH_SETUP:-}" in
  1|true|TRUE|yes|YES)
    setup_mode=1
    ;;
esac

require_command uname
require_command mktemp
require_command curl
require_command tar

os="$(uname -s)"
arch="$(uname -m)"

case "$os:$arch" in
  Linux:x86_64|Linux:amd64)
    artifact="linux-amd64"
    artifact_label="Linux x86_64"
    ;;
  Darwin:arm64|Darwin:aarch64)
    artifact="darwin-arm64"
    artifact_label="macOS Apple Silicon"
    ;;
  *)
    echo "Unsupported platform: $os/$arch" >&2
    exit 1
    ;;
esac

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT INT TERM
archive_path="$tmp_dir/rgh.tar.gz"
download_url="$shell_base_url/rgh/download/$artifact"

echo "Downloading $artifact_label build from $download_url" >&2
echo "Saving archive to $archive_path" >&2
if [ -t 2 ]; then
  curl -fL --progress-bar "$download_url" -o "$archive_path"
else
  curl -fsSL "$download_url" -o "$archive_path"
fi

mkdir -p "$install_dir"
rm -f "$legacy_install_path"
tar -xzf "$archive_path" -C "$tmp_dir"
rm -rf "$install_dir/rgh.dylibs"
if [ -d "$tmp_dir/rgh.dylibs" ]; then
  cp -R "$tmp_dir/rgh.dylibs" "$install_dir/rgh.dylibs"
  chmod -R 0755 "$install_dir/rgh.dylibs"
fi
cp "$tmp_dir/rgh" "$install_dir/rgh"
chmod 0755 "$install_dir/rgh"

echo "Installed rgh to $install_dir/rgh"
case ":$PATH:" in
  *":$install_dir:"*) ;;
  *)
    echo "Add $install_dir to PATH to run rgh directly." >&2
    ;;
esac

if [ "$setup_mode" -eq 1 ]; then
  echo "Starting Gitoku sign-in..." >&2
  if [ -r /dev/tty ] && [ -w /dev/tty ]; then
    "$install_dir/rgh" auth login </dev/tty >/dev/tty 2>/dev/tty
  else
    "$install_dir/rgh" auth login
  fi
fi
