#!/bin/sh
# CoreLink CLI installer — served from https://get.corelink.io.
# Source: github.com/humangr-labs/corelink-cli :: apps/get-corelink-worker.
# Re-run is safe: writes to /usr/local/bin/corelink and ~/.corelink/config.toml.
set -eu

TOKEN=""
REGION=""
while [ $# -gt 0 ]; do
  case "$1" in
    --token=*) TOKEN="${1#--token=}" ;;
    --region=*) REGION="${1#--region=}" ;;
    *) echo "WARN: ignoring unknown arg: $1" >&2 ;;
  esac
  shift
done

if [ -z "$TOKEN" ]; then
  echo "FATAL: --token required" >&2
  echo "Usage: curl -fsSL https://get.corelink.io | sh -s -- --token=<PAT> [--region=<region>]" >&2
  exit 2
fi

OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

URL="https://github.com/humangr-labs/corelink-cli/releases/latest/download/corelink-${OS}-${ARCH}"

echo "Downloading CoreLink CLI from $URL ..."
if ! curl -fsSL "$URL" -o /tmp/corelink; then
  echo "FATAL: failed to download $URL" >&2
  echo "Check https://github.com/humangr-labs/corelink-cli/releases for available binaries." >&2
  exit 3
fi
chmod +x /tmp/corelink

if [ "$(id -u)" -eq 0 ]; then
  mv /tmp/corelink /usr/local/bin/corelink
else
  sudo mv /tmp/corelink /usr/local/bin/corelink
fi

mkdir -p "$HOME/.corelink"
cat > "$HOME/.corelink/config.toml" <<EOF
token = "$TOKEN"
region = "${REGION:-auto}"
endpoint = "https://corelink-api.humangr.com"
EOF
chmod 600 "$HOME/.corelink/config.toml"

corelink ping
echo "Next: cd into your Bazel repo, run: corelink bazel-init"
