#!/usr/bin/env bash
set -euo pipefail

# Reoclo Runner Installer
# Usage:     curl -sSL https://get.reoclo.com | bash -s -- --token <TOKEN>
# Custom GW: curl -sSL https://get.reoclo.com | bash -s -- --token <TOKEN> --gateway <URL>
# Uninstall: curl -sSL https://get.reoclo.com | bash -s -- --uninstall
# Diagnose:  curl -sSL https://get.reoclo.com | bash -s -- --check
# Supports: Linux (systemd) and macOS (launchd)

VERSION=""
INSTALL_DIR="/usr/local/bin"
CONFIG_DIR="/etc/reoclo"
BINARY_NAME="reoclo-runner"
SERVICE_NAME="reoclo-runner"
CDN_URL="${CDN_URL:-https://cdn.reoclo.com}"

# macOS launchd
PLIST_LABEL="com.reoclo.runner"
PLIST_PATH="/Library/LaunchDaemons/${PLIST_LABEL}.plist"
LOG_DIR="/var/log"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info()  { echo -e "${BLUE}[INFO]${NC}  $*"; }
ok()    { echo -e "${GREEN}[OK]${NC}    $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
die()   { error "$*"; exit 1; }

# --- Parse arguments ---
TOKEN=""
GATEWAY_URL="wss://api.reoclo.com/ws/runner"
UNINSTALL=false
CHECK_ONLY=false

while [[ $# -gt 0 ]]; do
  case "$1" in
    --token)     TOKEN="$2"; shift 2 ;;
    --gateway)   GATEWAY_URL="$2"; shift 2 ;;
    --version)   VERSION="$2"; shift 2 ;;
    --uninstall) UNINSTALL=true; shift ;;
    --check)     CHECK_ONLY=true; shift ;;
    --help|-h)   echo "Usage: $0 [--token <TOKEN>] [--gateway <URL>] [--version <VERSION>] [--uninstall] [--check]"; exit 0 ;;
    *) die "Unknown argument: $1" ;;
  esac
done

# --- Uninstall mode ---
if [[ "$UNINSTALL" == true ]]; then
  info "Uninstalling Reoclo Runner..."

  # Detect OS for uninstall (before main OS detection)
  _UNINSTALL_OS="$(uname -s)"
  _SUDO=""
  if [[ "$(id -u)" -ne 0 ]]; then
    if command -v sudo >/dev/null 2>&1; then
      _SUDO="sudo"
    else
      die "Root privileges required and sudo is not installed. Re-run as root."
    fi
  fi

  if [[ "$_UNINSTALL_OS" == "Linux" ]]; then
    if $_SUDO systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
      info "Stopping service..."
      $_SUDO systemctl stop "$SERVICE_NAME"
    fi
    if $_SUDO systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
      $_SUDO systemctl disable "$SERVICE_NAME" 2>/dev/null || true
    fi
    if [[ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]]; then
      $_SUDO rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
      $_SUDO systemctl daemon-reload
    fi
  elif [[ "$_UNINSTALL_OS" == "Darwin" ]]; then
    if $_SUDO launchctl list "$PLIST_LABEL" >/dev/null 2>&1; then
      info "Stopping service..."
      $_SUDO launchctl bootout "system/${PLIST_LABEL}" 2>/dev/null || \
        $_SUDO launchctl unload "$PLIST_PATH" 2>/dev/null || true
    fi
    $_SUDO rm -f "$PLIST_PATH"
    $_SUDO rm -f "${LOG_DIR}/reoclo-runner.log"
  else
    warn "Unknown OS: $_UNINSTALL_OS. Removing binary and config only."
  fi

  $_SUDO rm -f "${INSTALL_DIR}/${BINARY_NAME}"
  $_SUDO rm -f "${INSTALL_DIR}/${BINARY_NAME}.old"
  $_SUDO rm -rf "$CONFIG_DIR"

  ok "Reoclo Runner uninstalled successfully"
  exit 0
fi

if [[ "$CHECK_ONLY" != true ]]; then
  [[ -z "$TOKEN" ]] && die "Missing required --token argument"
fi

# --- Resolve version (fetch latest from CDN if not pinned) ---
if [[ "$CHECK_ONLY" != true ]] && [[ -z "$VERSION" ]]; then
  VERSION=$(curl -sSL "${CDN_URL}/releases/runner/latest-version.txt" 2>/dev/null | tr -d '[:space:]')
  if [[ -z "$VERSION" ]]; then
    VERSION="latest"
  fi
fi

# --- Detect platform (early, needed for prerequisite checks) ---
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

case "$OS" in
  linux)  ;;
  darwin) ;;
  *) die "Unsupported OS: $OS (only Linux and macOS are supported)" ;;
esac

case "$ARCH" in
  x86_64|amd64) ARCH="x64" ;;
  aarch64|arm64) ARCH="arm64" ;;
  *) die "Unsupported architecture: $ARCH (only x64 and arm64 are supported)" ;;
esac

# --- Sudo check ---
SUDO=""
if [[ "$(id -u)" -ne 0 ]]; then
  if ! command -v sudo >/dev/null 2>&1; then
    if [[ "$CHECK_ONLY" == true ]]; then
      warn "sudo not installed — check will run with limited privileges"
    else
      die "Root privileges required and sudo is not installed. Re-run as root."
    fi
  elif [[ "$CHECK_ONLY" == true ]]; then
    # In check mode, use non-interactive sudo so we never prompt for a password.
    # If credentials aren't cached, $SUDO stays empty and we just skip root checks.
    if sudo -n true 2>/dev/null; then
      SUDO="sudo -n"
    fi
  else
    warn "Root privileges required. Requesting sudo..."
    if ! sudo -v; then
      die "Failed to obtain sudo privileges"
    fi
    SUDO="sudo"
    # Keep sudo alive for the duration of the install
    while true; do sudo -n true; sleep 50; kill -0 "$$" || exit; done 2>/dev/null &
  fi
fi

# --- Check prerequisites ---
info "Checking prerequisites..."

command -v curl >/dev/null 2>&1 || die "curl is required but not installed"
command -v docker >/dev/null 2>&1 || die "Docker is required but not installed"

if [[ "$OS" == "linux" ]]; then
  command -v systemctl >/dev/null 2>&1 || die "systemd is required (systemctl not found)"
elif [[ "$OS" == "darwin" ]]; then
  command -v launchctl >/dev/null 2>&1 || die "launchctl is required but not found"
fi

# --- Detect Docker mode (rootless vs rootful) ---
# Rootless Docker runs as a specific non-root user, so `sudo docker info`
# fails (sudo strips DOCKER_HOST from the env and root has no socket). We
# test docker access as the invoking user first; if it works and reports
# the rootless security option, the runner must be installed as THAT user
# instead of the dedicated `reoclo` system user.
ROOTLESS_DOCKER=false
ROOTLESS_USER=""
ROOTLESS_UID=""
ROOTLESS_DOCKER_HOST=""

if [[ "$OS" == "linux" ]]; then
  if [[ "$(id -u)" -ne 0 ]]; then
    # Running as non-root — probe docker in the current shell context
    if docker info >/dev/null 2>&1 && \
       docker info --format '{{.SecurityOptions}}' 2>/dev/null | grep -qi rootless; then
      ROOTLESS_DOCKER=true
      ROOTLESS_USER="$(id -un)"
      ROOTLESS_UID="$(id -u)"
      ROOTLESS_DOCKER_HOST="${DOCKER_HOST:-unix:///run/user/${ROOTLESS_UID}/docker.sock}"
    fi
  elif [[ -n "${SUDO_USER:-}" ]] && [[ "$SUDO_USER" != "root" ]]; then
    # Running as root via sudo — probe rootless for the original user
    if sudo -u "$SUDO_USER" -H bash -lc 'docker info' >/dev/null 2>&1 && \
       sudo -u "$SUDO_USER" -H bash -lc 'docker info --format "{{.SecurityOptions}}"' 2>/dev/null | grep -qi rootless; then
      ROOTLESS_DOCKER=true
      ROOTLESS_USER="$SUDO_USER"
      ROOTLESS_UID="$(id -u "$SUDO_USER")"
      ROOTLESS_DOCKER_HOST="$(sudo -u "$SUDO_USER" -H bash -lc 'echo "${DOCKER_HOST:-}"' 2>/dev/null || true)"
      [[ -z "$ROOTLESS_DOCKER_HOST" ]] && \
        ROOTLESS_DOCKER_HOST="unix:///run/user/${ROOTLESS_UID}/docker.sock"
    fi
  fi
fi

# Verify Docker is running
DOCKER_RUNNING=false
if [[ "$ROOTLESS_DOCKER" == true ]]; then
  info "Detected rootless Docker (user: ${ROOTLESS_USER}, socket: ${ROOTLESS_DOCKER_HOST})"
  DOCKER_RUNNING=true
elif [[ -n "$SUDO" ]] && $SUDO docker info >/dev/null 2>&1; then
  DOCKER_RUNNING=true
elif docker info >/dev/null 2>&1; then
  # User has direct access (rootful docker + user in docker group)
  DOCKER_RUNNING=true
fi

if [[ "$DOCKER_RUNNING" != true ]] && [[ "$CHECK_ONLY" != true ]]; then
  die "Docker is installed but not running"
fi

ok "Prerequisites satisfied"

# --- Determine runner user ---
# Rootful mode: create a dedicated `reoclo` system user and add it to the
# docker group so it can talk to the rootful Docker daemon.
# Rootless mode: reuse the rootless-docker user (they already own the socket).
# No new user is created; no docker group membership needed.
RUNNER_USER="reoclo"
RUNNER_GROUP="reoclo"
if [[ "$OS" == "linux" ]] && [[ "$ROOTLESS_DOCKER" == true ]]; then
  RUNNER_USER="$ROOTLESS_USER"
  RUNNER_GROUP="$(id -gn "$ROOTLESS_USER" 2>/dev/null || echo "$ROOTLESS_USER")"
fi

# --- Check mode: print detection results and exit ---
# This path is used by the e2e tests (and by end users diagnosing install
# issues) to inspect what mode the installer would use without touching the
# system. It exits before any files are written or services installed.
if [[ "$CHECK_ONLY" == true ]]; then
  cat << CHECK
OS=$OS
ARCH=$ARCH
DOCKER_RUNNING=$DOCKER_RUNNING
ROOTLESS_DOCKER=$ROOTLESS_DOCKER
ROOTLESS_USER=$ROOTLESS_USER
ROOTLESS_UID=$ROOTLESS_UID
ROOTLESS_DOCKER_HOST=$ROOTLESS_DOCKER_HOST
RUNNER_USER=$RUNNER_USER
RUNNER_GROUP=$RUNNER_GROUP
GATEWAY_URL=$GATEWAY_URL
CHECK
  ok "Check complete"
  exit 0
fi

# --- Create reoclo system user and install sudoers rules (Linux only) ---
if [[ "$OS" == "linux" ]]; then
  if [[ "$ROOTLESS_DOCKER" == true ]]; then
    info "Runner will run as user: ${RUNNER_USER} (rootless Docker)"
    # Enable lingering so the user session (and rootless Docker) stays alive
    # across reboots and logouts — required for the runner to start on boot.
    if command -v loginctl >/dev/null 2>&1; then
      $SUDO loginctl enable-linger "$RUNNER_USER" 2>/dev/null || \
        warn "Failed to enable linger for ${RUNNER_USER} — runner may not start on boot"
    fi
  else
    if ! id -u reoclo >/dev/null 2>&1; then
      info "Creating reoclo system user..."
      $SUDO useradd --system --shell /usr/sbin/nologin --home-dir /etc/reoclo --create-home reoclo
      ok "Created reoclo user"
    else
      info "reoclo user already exists"
    fi

    # Add to docker group if it exists
    if getent group docker >/dev/null 2>&1; then
      $SUDO usermod -aG docker reoclo
      ok "Added reoclo to docker group"
    else
      warn "Docker group not found — runner won't have Docker access"
    fi
  fi

  # Install sudoers whitelist for the runner user
  info "Installing sudoers rules for ${RUNNER_USER}..."
  $SUDO tee /etc/sudoers.d/reoclo-runner > /dev/null << SUDOERS
# Reoclo Runner — limited privilege escalation
${RUNNER_USER} ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart *, /usr/bin/systemctl stop *, /usr/bin/systemctl start *
${RUNNER_USER} ALL=(ALL) NOPASSWD: /usr/sbin/reboot, /usr/sbin/shutdown
${RUNNER_USER} ALL=(ALL) NOPASSWD: /usr/bin/ufw *
${RUNNER_USER} ALL=(ALL) NOPASSWD: /usr/sbin/nft *
${RUNNER_USER} ALL=(ALL) NOPASSWD: /usr/sbin/iptables *
SUDOERS
  $SUDO chmod 0440 /etc/sudoers.d/reoclo-runner
  ok "Sudoers rules installed"
fi

info "Platform: ${OS}-${ARCH}"

# --- Download binary ---
if [ "$VERSION" = "latest" ]; then
  DOWNLOAD_URL="${CDN_URL}/releases/runner/latest/${BINARY_NAME}-${OS}-${ARCH}"
else
  DOWNLOAD_URL="${CDN_URL}/releases/runner/${VERSION}/${BINARY_NAME}-${OS}-${ARCH}"
fi
info "Downloading ${BINARY_NAME} v${VERSION}..."

TEMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TEMP_DIR"' EXIT

TEMP_BIN="${TEMP_DIR}/${BINARY_NAME}"
if ! curl -fsSL -o "$TEMP_BIN" "$DOWNLOAD_URL"; then
  die "Failed to download from ${DOWNLOAD_URL}"
fi

chmod +x "$TEMP_BIN"
ok "Downloaded successfully"

# --- Uninstall existing runner if present ---
if [[ "$OS" == "linux" ]]; then
  if $SUDO systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
    warn "Existing runner detected. Stopping service..."
    $SUDO systemctl stop "$SERVICE_NAME"
  fi

  if $SUDO systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
    $SUDO systemctl disable "$SERVICE_NAME" 2>/dev/null || true
  fi

  if [[ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]]; then
    warn "Removing old systemd unit..."
    $SUDO rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
    $SUDO systemctl daemon-reload
  fi
elif [[ "$OS" == "darwin" ]]; then
  if $SUDO launchctl list "$PLIST_LABEL" >/dev/null 2>&1; then
    warn "Existing runner detected. Stopping service..."
    $SUDO launchctl bootout "system/${PLIST_LABEL}" 2>/dev/null || \
      $SUDO launchctl unload "$PLIST_PATH" 2>/dev/null || true
  fi

  if [[ -f "$PLIST_PATH" ]]; then
    warn "Removing old launchd plist..."
    $SUDO rm -f "$PLIST_PATH"
  fi
fi

if [[ -f "${INSTALL_DIR}/${BINARY_NAME}" ]]; then
  warn "Removing old binary..."
  $SUDO rm -f "${INSTALL_DIR}/${BINARY_NAME}"
  $SUDO rm -f "${INSTALL_DIR}/${BINARY_NAME}.old"
fi

if [[ -d "$CONFIG_DIR" ]]; then
  warn "Removing old config..."
  $SUDO rm -rf "$CONFIG_DIR"
fi

ok "Clean slate ready"

# --- Install binary ---
info "Installing to ${INSTALL_DIR}/${BINARY_NAME}..."

$SUDO cp "$TEMP_BIN" "${INSTALL_DIR}/${BINARY_NAME}"
$SUDO chmod +x "${INSTALL_DIR}/${BINARY_NAME}"

ok "Binary installed to ${INSTALL_DIR}/${BINARY_NAME}"

# --- Create config directory ---
$SUDO mkdir -p "$CONFIG_DIR"
if [[ "$OS" == "linux" ]]; then
  $SUDO chown "${RUNNER_USER}:${RUNNER_GROUP}" "$CONFIG_DIR"
fi
$SUDO chmod 0700 "$CONFIG_DIR"
$SUDO mkdir -p /tmp/reoclo-

# --- Initial registration ---
info "Registering runner with platform..."

if [[ "$OS" == "linux" ]]; then
  if [[ "$ROOTLESS_DOCKER" == true ]]; then
    # In rootless mode we must inject DOCKER_HOST so the runner talks to the
    # user's rootless socket (sudo -u doesn't carry DOCKER_HOST through).
    $SUDO -u "$RUNNER_USER" -H env \
      "DOCKER_HOST=$ROOTLESS_DOCKER_HOST" \
      "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \
      "${INSTALL_DIR}/${BINARY_NAME}" \
      --token "$TOKEN" \
      --gateway "$GATEWAY_URL" &
  else
    $SUDO -u "$RUNNER_USER" "${INSTALL_DIR}/${BINARY_NAME}" \
      --token "$TOKEN" \
      --gateway "$GATEWAY_URL" &
  fi
else
  $SUDO "${INSTALL_DIR}/${BINARY_NAME}" \
    --token "$TOKEN" \
    --gateway "$GATEWAY_URL" &
fi

RUNNER_PID=$!

# Wait up to 30 seconds for registration
for i in $(seq 1 30); do
  if [[ -f "${CONFIG_DIR}/runner.json" ]] || $SUDO test -f "${CONFIG_DIR}/runner.json"; then
    ok "Runner registered successfully"
    kill "$RUNNER_PID" 2>/dev/null || true
    wait "$RUNNER_PID" 2>/dev/null || true
    break
  fi
  sleep 1
done

if ! { [[ -f "${CONFIG_DIR}/runner.json" ]] || $SUDO test -f "${CONFIG_DIR}/runner.json"; }; then
  kill "$RUNNER_PID" 2>/dev/null || true
  wait "$RUNNER_PID" 2>/dev/null || true
  die "Registration timed out. Check your token and gateway URL."
fi

# --- Install service ---
if [[ "$OS" == "linux" ]]; then
  info "Installing systemd service..."

  if [[ "$ROOTLESS_DOCKER" == true ]]; then
    # Rootless mode: run as the rootless-docker user, inject DOCKER_HOST, and
    # drop Requires=docker.service (rootless Docker is a user-level unit, not
    # the system docker.service). ProtectHome is omitted so the runner can
    # reach the rootless Docker state under ~/.local/share/docker.
    $SUDO tee "/etc/systemd/system/${SERVICE_NAME}.service" > /dev/null << UNIT
[Unit]
Description=Reoclo Runner Agent
Documentation=https://docs.reoclo.com/runner
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/reoclo-runner --config /etc/reoclo/runner.json
Restart=always
RestartSec=5
User=${RUNNER_USER}
Group=${RUNNER_GROUP}
Environment="DOCKER_HOST=${ROOTLESS_DOCKER_HOST}"
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Security hardening (ProtectHome omitted — rootless Docker state lives under ~)
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictRealtime=yes
SystemCallArchitectures=native

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=reoclo-runner

[Install]
WantedBy=multi-user.target
UNIT
  else
    $SUDO tee "/etc/systemd/system/${SERVICE_NAME}.service" > /dev/null << 'UNIT'
[Unit]
Description=Reoclo Runner Agent
Documentation=https://docs.reoclo.com/runner
After=network-online.target docker.service
Wants=network-online.target
Requires=docker.service

[Service]
Type=simple
ExecStart=/usr/local/bin/reoclo-runner --config /etc/reoclo/runner.json
Restart=always
RestartSec=5
User=reoclo
Group=reoclo

# Security hardening (NoNewPrivileges omitted to allow sudoers whitelist)
ProtectHome=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictRealtime=yes
SystemCallArchitectures=native

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=reoclo-runner

[Install]
WantedBy=multi-user.target
UNIT
  fi

  $SUDO systemctl daemon-reload
  $SUDO systemctl enable "$SERVICE_NAME"
  $SUDO systemctl start "$SERVICE_NAME"

  # Wait for initial connection, then restart to ensure fresh capabilities
  # are reported (the temporary registration process may have sent stale data)
  sleep 8
  $SUDO systemctl restart "$SERVICE_NAME"

  ok "Service installed and started"

elif [[ "$OS" == "darwin" ]]; then
  info "Installing launchd service..."

  $SUDO tee "$PLIST_PATH" > /dev/null << PLIST
<?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>${PLIST_LABEL}</string>
    <key>ProgramArguments</key>
    <array>
        <string>${INSTALL_DIR}/${BINARY_NAME}</string>
        <string>--config</string>
        <string>${CONFIG_DIR}/runner.json</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>ThrottleInterval</key>
    <integer>5</integer>
    <key>StandardOutPath</key>
    <string>${LOG_DIR}/reoclo-runner.log</string>
    <key>StandardErrorPath</key>
    <string>${LOG_DIR}/reoclo-runner.log</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
    </dict>
</dict>
</plist>
PLIST

  $SUDO launchctl bootstrap system "$PLIST_PATH" 2>/dev/null || \
    $SUDO launchctl load -w "$PLIST_PATH"

  ok "Service installed and started"
fi

# --- Verify ---
sleep 2
if [[ "$OS" == "linux" ]]; then
  if $SUDO systemctl is-active --quiet "$SERVICE_NAME"; then
    ok "Runner is active and running"
  else
    warn "Service started but may not be fully ready yet"
    warn "Check status: systemctl status ${SERVICE_NAME}"
    warn "Check logs:   journalctl -u ${SERVICE_NAME} -f"
  fi
elif [[ "$OS" == "darwin" ]]; then
  if $SUDO launchctl list "$PLIST_LABEL" >/dev/null 2>&1; then
    ok "Runner is active and running"
  else
    warn "Service started but may not be fully ready yet"
    warn "Check status: sudo launchctl list ${PLIST_LABEL}"
    warn "Check logs:   tail -f ${LOG_DIR}/reoclo-runner.log"
  fi
fi

echo ""
if [[ "$OS" == "linux" ]]; then
  echo -e "${GREEN}╔═══════════════════════════════════════════════════╗${NC}"
  echo -e "${GREEN}║  Reoclo Runner installed successfully!            ║${NC}"
  echo -e "${GREEN}╠═══════════════════════════════════════════════════╣${NC}"
  echo -e "${GREEN}║                                                   ║${NC}"
  echo -e "${GREEN}║  Binary:  ${INSTALL_DIR}/${BINARY_NAME}${NC}           ${GREEN}║${NC}"
  echo -e "${GREEN}║  Config:  ${CONFIG_DIR}/runner.json${NC}                ${GREEN}║${NC}"
  echo -e "${GREEN}║  Service: ${SERVICE_NAME}${NC}                          ${GREEN}║${NC}"
  echo -e "${GREEN}║                                                   ║${NC}"
  echo -e "${GREEN}║  Commands:                                        ║${NC}"
  echo -e "${GREEN}║    Status: systemctl status ${SERVICE_NAME}${NC}        ${GREEN}║${NC}"
  echo -e "${GREEN}║    Logs:   journalctl -u ${SERVICE_NAME} -f${NC}       ${GREEN}║${NC}"
  echo -e "${GREEN}║    Stop:   systemctl stop ${SERVICE_NAME}${NC}          ${GREEN}║${NC}"
  echo -e "${GREEN}║    Start:  systemctl start ${SERVICE_NAME}${NC}         ${GREEN}║${NC}"
  echo -e "${GREEN}║                                                   ║${NC}"
  echo -e "${GREEN}╚═══════════════════════════════════════════════════╝${NC}"
elif [[ "$OS" == "darwin" ]]; then
  echo -e "${GREEN}╔═══════════════════════════════════════════════════════════╗${NC}"
  echo -e "${GREEN}║  Reoclo Runner installed successfully!                    ║${NC}"
  echo -e "${GREEN}╠═══════════════════════════════════════════════════════════╣${NC}"
  echo -e "${GREEN}║                                                           ║${NC}"
  echo -e "${GREEN}║  Binary:  ${INSTALL_DIR}/${BINARY_NAME}${NC}                   ${GREEN}║${NC}"
  echo -e "${GREEN}║  Config:  ${CONFIG_DIR}/runner.json${NC}                        ${GREEN}║${NC}"
  echo -e "${GREEN}║  Service: ${PLIST_LABEL}${NC}                              ${GREEN}║${NC}"
  echo -e "${GREEN}║  Logs:    ${LOG_DIR}/reoclo-runner.log${NC}                     ${GREEN}║${NC}"
  echo -e "${GREEN}║                                                           ║${NC}"
  echo -e "${GREEN}║  Commands:                                                ║${NC}"
  echo -e "${GREEN}║    Status: sudo launchctl list ${PLIST_LABEL}${NC}         ${GREEN}║${NC}"
  echo -e "${GREEN}║    Logs:   tail -f ${LOG_DIR}/reoclo-runner.log${NC}            ${GREEN}║${NC}"
  echo -e "${GREEN}║    Stop:   sudo launchctl bootout system/${PLIST_LABEL}${NC} ${GREEN}║${NC}"
  echo -e "${GREEN}║    Start:  sudo launchctl bootstrap system ${PLIST_PATH}${NC} ${GREEN}║${NC}"
  echo -e "${GREEN}║                                                           ║${NC}"
  echo -e "${GREEN}╚═══════════════════════════════════════════════════════════╝${NC}"
fi
