#!/bin/bash
# MacBuildCloud: turn your dedicated Mac mini into a GitHub Actions self-hosted runner.
#
#   Install:  bash github-runner.sh install <repository or organisation URL>
#   Status:   bash github-runner.sh status
#   Remove:   bash github-runner.sh remove
#
# Runs as your own (standard) user. No sudo, nothing outside your home folder
# except one line in your user crontab, so the runner starts again after the
# Mac restarts. The registration token is read from the keyboard and is never
# written to disk or shown on screen.
#
# Guide: https://macbuildcloud.com/use/github-actions-runner/
set -euo pipefail

DIR="${MBC_RUNNER_DIR:-$HOME/actions-runner}"
LABELS="${MBC_RUNNER_LABELS:-macbuildcloud,apple-m6}"
NAME="${MBC_RUNNER_NAME:-$(scutil --get LocalHostName 2>/dev/null || hostname -s)-$(id -un)}"
LOOP="$DIR/mbc-run-forever.sh"
CRON_TAG="# macbuildcloud-github-runner"

say()  { printf '%s\n' "$*"; }
fail() { printf 'Error: %s\n' "$*" >&2; exit 1; }

read_token() {   # <prompt>
  local t=""
  if [ -n "${MBC_RUNNER_TOKEN:-}" ]; then t="$MBC_RUNNER_TOKEN"
  else
    printf '%s' "$1" >&2
    IFS= read -rs t || true
    printf '\n' >&2
  fi
  t="$(printf '%s' "$t" | tr -d '[:space:]')"
  [ -n "$t" ] || fail "no token entered."
  printf '%s' "$t"
}

running_pid() { pgrep -u "$(id -u)" -f "$DIR/bin/Runner.Listener" 2>/dev/null | head -1 || true; }

download() {
  [ "$(uname -s)" = Darwin ] && [ "$(uname -m)" = arm64 ] || fail "this script is for Apple silicon Macs."
  say "Finding the latest GitHub Actions runner release..."
  local json ver url sha got
  json="$(curl -fsSL https://api.github.com/repos/actions/runner/releases/latest)" \
    || fail "could not reach api.github.com."
  ver="$(printf '%s' "$json" | sed -n 's/.*"tag_name": *"v\([0-9.]*\)".*/\1/p' | head -1)"
  [ -n "$ver" ] || fail "could not read the latest runner version from GitHub."
  url="https://github.com/actions/runner/releases/download/v${ver}/actions-runner-osx-arm64-${ver}.tar.gz"
  # GitHub publishes each package's SHA-256 in the release notes between these markers.
  sha="$(printf '%s' "$json" | sed -n 's/.*<!-- BEGIN SHA osx-arm64 -->\([0-9a-f]\{64\}\)<!-- END SHA osx-arm64 -->.*/\1/p' | head -1)"
  [ -n "$sha" ] || fail "could not read the checksum for runner ${ver} from GitHub."
  mkdir -p "$DIR"
  say "Downloading runner ${ver}..."
  curl -fsSL "$url" -o "$DIR/runner.tar.gz" || fail "download failed."
  got="$(shasum -a 256 "$DIR/runner.tar.gz" | awk '{print $1}')"
  [ "$got" = "$sha" ] || { rm -f "$DIR/runner.tar.gz"; fail "checksum mismatch, download discarded."; }
  tar -xzf "$DIR/runner.tar.gz" -C "$DIR"
  rm -f "$DIR/runner.tar.gz"
  say "Runner ${ver} downloaded and checksum verified."
}

write_loop() {
  cat > "$LOOP" <<EOF
#!/bin/bash
# Started by cron at boot and by github-runner.sh install. Restarts the runner if it exits.
cd "$DIR" || exit 1
while true; do
  ./run.sh >> "$DIR/mbc-runner.log" 2>&1
  sleep 10
done
EOF
  chmod 755 "$LOOP"
}

cron_add() {
  local cur
  cur="$(crontab -l 2>/dev/null | grep -v "$CRON_TAG" || true)"
  printf '%s\n@reboot /bin/bash "%s" >/dev/null 2>&1 %s\n' "$cur" "$LOOP" "$CRON_TAG" | sed '/^$/d' | crontab -
}

cron_remove() {
  local cur
  cur="$(crontab -l 2>/dev/null | grep -v "$CRON_TAG" || true)"
  if [ -n "$cur" ]; then printf '%s\n' "$cur" | crontab -; else crontab -r 2>/dev/null || true; fi
}

stop_runner() {
  pkill -u "$(id -u)" -f "$LOOP" 2>/dev/null || true
  pkill -u "$(id -u)" -f "$DIR/bin/Runner.Listener" 2>/dev/null || true
  sleep 2
}

start_runner() {
  nohup /bin/bash "$LOOP" >/dev/null 2>&1 &
  local i
  for i in $(seq 1 30); do
    if grep -q "Listening for Jobs" "$DIR/mbc-runner.log" 2>/dev/null; then return 0; fi
    sleep 2
  done
  return 1
}

cmd_install() {
  local url="${1:-}"
  [[ "$url" =~ ^https://github\.com/[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)?/?$ ]] \
    || fail "give the repository or organisation URL, e.g. https://github.com/you/your-app"
  [ ! -f "$DIR/.runner" ] || fail "a runner is already set up in $DIR. Run 'bash $0 remove' first."
  say "This sets up a GitHub Actions runner for $url"
  say "Get a registration token on GitHub: Settings > Actions > Runners > New self-hosted runner"
  say "(it is the value after --token in the Configure step, and it expires after one hour)."
  local token; token="$(read_token 'Paste the registration token (hidden): ')"
  download
  say "Registering as '$NAME' with labels: self-hosted, macOS, ARM64, $LABELS"
  ( cd "$DIR" && ./config.sh --unattended --url "$url" --token "$token" --name "$NAME" \
        --labels "$LABELS" --work _work --replace ) >/dev/null \
    || fail "GitHub refused the registration. The token may have expired: get a new one and run install again."
  write_loop
  cron_add
  : > "$DIR/mbc-runner.log"
  start_runner || fail "the runner did not come online. See $DIR/mbc-runner.log"
  say ""
  say "Done. The runner is online and will start again on its own after a restart."
  say "Use it in a workflow with:   runs-on: [self-hosted, macbuildcloud]"
}

cmd_status() {
  [ -f "$DIR/.runner" ] || { say "No runner is set up in $DIR."; return 0; }
  local pid; pid="$(running_pid)"
  say "Runner folder: $DIR"
  say "Registered as: $(sed -n 's/.*"agentName": *"\([^"]*\)".*/\1/p' "$DIR/.runner" | head -1)"
  say "Repository:    $(sed -n 's/.*"gitHubUrl": *"\([^"]*\)".*/\1/p' "$DIR/.runner" | head -1)"
  say "Running:       $([ -n "$pid" ] && echo "yes (pid $pid)" || echo no)"
  say "Starts at boot: $(crontab -l 2>/dev/null | grep -q "$CRON_TAG" && echo yes || echo no)"
  say "Last log line: $(grep -v '^$' "$DIR/mbc-runner.log" 2>/dev/null | tail -1)"
}

cmd_remove() {
  [ -f "$DIR/.runner" ] || { cron_remove; stop_runner; say "No runner is set up in $DIR. Nothing to remove."; return 0; }
  say "Get a removal token on GitHub: Settings > Actions > Runners > (this runner) > Remove"
  say "(it is the value after --token in the command shown there)."
  local token; token="$(read_token 'Paste the removal token (hidden): ')"
  stop_runner
  cron_remove
  ( cd "$DIR" && ./config.sh remove --token "$token" ) >/dev/null \
    || fail "GitHub refused the removal (token expired?). The runner is stopped and will not start at boot; get a new removal token and run remove again."
  rm -rf "$DIR"
  say "Removed. The runner is unregistered from GitHub and deleted from this Mac."
}

case "${1:-}" in
  install) shift; cmd_install "$@" ;;
  status)  cmd_status ;;
  remove)  cmd_remove ;;
  *) say "Usage: bash $0 install <repository or organisation URL> | status | remove"; exit 2 ;;
esac
