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

repo="${MINI_REPO:-https://github.com/happenings-dk/mini.git}"
owner_repo="${MINI_GITHUB_REPO:-happenings-dk/mini}"
download_base="${MINI_DOWNLOAD_BASE:-https://minicli.site/downloads/mini/latest}"
prefix="${MINI_PREFIX:-$HOME/.local}"
src="${MINI_SOURCE_DIR:-$HOME/.mini/src/mini}"
bin_dir="$prefix/bin"
bin="$bin_dir/mini"

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

need curl

mkdir -p "$bin_dir"

os="$(uname -s)"
arch="$(uname -m)"
case "$arch" in
  arm64|aarch64) arch="arm64" ;;
  x86_64|amd64) arch="x86_64" ;;
esac

asset="mini_${os}_${arch}.tar.gz"
primary_url="${download_base%/}/${asset}"
github_url="https://github.com/${owner_repo}/releases/latest/download/${asset}"
tmp="$(mktemp -d)"
cleanup() {
  rm -rf "$tmp"
}
trap cleanup EXIT

if [ "${MINI_FROM_SOURCE:-0}" != "1" ]; then
  if curl -fsSL "$primary_url" -o "$tmp/$asset" || curl -fsSL "$github_url" -o "$tmp/$asset"; then
    tar -xzf "$tmp/$asset" -C "$tmp"
    cp "$tmp/mini_${os}_${arch}/mini" "$bin"
    chmod +x "$bin"
    echo "Installed mini at $bin"
    case ":$PATH:" in
      *":$bin_dir:"*) ;;
      *) echo "Add $bin_dir to PATH before running mini." ;;
    esac
    echo
    echo "Bootstrap this Mac mini:"
    echo "  mini setup --yes --name my-mini --domain example.com"
    exit 0
  fi
  echo "No release binary found at $primary_url or $github_url; falling back to source install." >&2
fi

need git
need go
mkdir -p "$(dirname "$src")"
if [ -d "$src/.git" ]; then
  git -C "$src" pull --ff-only
else
  git clone "$repo" "$src"
fi
go -C "$src" build -o "$bin" ./cmd/mini

echo "Installed mini at $bin"
case ":$PATH:" in
  *":$bin_dir:"*) ;;
  *) echo "Add $bin_dir to PATH before running mini." ;;
esac

echo
echo "Bootstrap this Mac mini:"
echo "  mini setup --yes --name my-mini --domain example.com"
