#!/usr/bin/env bash
#
# Shell script for macOS users to switch the OpenSSH agent between the provided
# built-in macOS OpenSSH agent, and the Homebrew-installed OpenSSH agent.
#
# The macOS OpenSSH agent doesn't support FIDO2 keys, thus the Homebrew OpenSSH
# agent is required.
#
# Lookup of the agent is done via UNIX socket and must explicitly be specified
# via SSH_AUTH_SOCK in the shell RC file.
#
set -euo pipefail

PLIST="$HOME/Library/LaunchAgents/homebrew.ssh-agent.plist"
SOCK="$HOME/.ssh/agent.sock"
APPLE_LABEL="com.openssh.ssh-agent"
BREW_LABEL="homebrew.ssh-agent"
UID_GUI="gui/$(id -u)"

status() {
    if launchctl print "$UID_GUI/$BREW_LABEL" &>/dev/null; then
        echo "active"
    else
        echo "inactive"
    fi
}

write_plist() {
    mkdir -p "$(dirname "$PLIST")"
    cat > "$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>${BREW_LABEL}</string>
  <key>ProgramArguments</key>
  <array>
    <string>/opt/homebrew/bin/ssh-agent</string>
    <string>-D</string>
    <string>-a</string>
    <string>${SOCK}</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
</dict>
</plist>
EOF
}

enable_brew() {
    echo "Switching to Homebrew ssh-agent..."
    write_plist
    launchctl disable "$UID_GUI/$APPLE_LABEL" 2>/dev/null || true
    launchctl bootout "$UID_GUI/$APPLE_LABEL" 2>/dev/null || true
    launchctl bootstrap "$UID_GUI" "$PLIST" 2>/dev/null || launchctl load "$PLIST"
    echo "Done. Homebrew ssh-agent is now active."
    echo "Make sure SSH_AUTH_SOCK=${SOCK} is set in your shell RC."
}

enable_apple() {
    echo "Switching back to Apple ssh-agent..."
    launchctl bootout "$UID_GUI/$BREW_LABEL" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
    rm -f "$PLIST"
    launchctl enable "$UID_GUI/$APPLE_LABEL" 2>/dev/null || true
    launchctl bootstrap "$UID_GUI" "/System/Library/LaunchAgents/com.openssh.ssh-agent.plist" 2>/dev/null || true
    echo "Done. Apple ssh-agent is now active, plist removed. Restart your terminal (or unset SSH_AUTH_SOCK)."
}

case "${1:-}" in
    brew|enable)
        enable_brew
        ;;
    apple|disable)
        enable_apple
        ;;
    toggle|"")
        if [[ "$(status)" == "active" ]]; then
            enable_apple
        else
            enable_brew
        fi
        ;;
    status)
        echo "Homebrew ssh-agent: $(status)"
        ;;
    *)
        echo "Usage: $0 [brew|apple|toggle|status]"
        exit 1
        ;;
esac
