#!/usr/bin/env bash
# BigBrother autostart -- Enable/disable auto-start on boot
# Manages: bigbrother-core, bigbrother-capture, bigbrother-watchdog
#
# Usage: autostart.sh enable | disable | status
set -euo pipefail

# ── Colors ──────────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

info()  { echo -e "${GREEN}[+]${NC} $*"; }
warn()  { echo -e "${YELLOW}[!]${NC} $*"; }
error() { echo -e "${RED}[-]${NC} $*"; }
step()  { echo -e "${CYAN}[*]${NC} ${BOLD}$*${NC}"; }

die() { error "$*"; exit 1; }

# ── Service list ─────────────────────────────────────────────────────────────
SERVICES=(
    bigbrother-core.service
    bigbrother-capture.service
    bigbrother-watchdog.service
)

# ── Root check ───────────────────────────────────────────────────────────────
require_root() {
    [[ $EUID -eq 0 ]] || die "Must be run as root (try: sudo $0 $*)"
}

# ── Usage ─────────────────────────────────────────────────────────────────────
usage() {
    echo "Usage: $0 <command>"
    echo ""
    echo "Commands:"
    echo "  enable   -- Enable and start all BigBrother services at boot"
    echo "  disable  -- Disable and stop all BigBrother services"
    echo "  status   -- Show enabled/running state of all services"
    exit 1
}

# ── Helpers ──────────────────────────────────────────────────────────────────
svc_is_enabled() {
    systemctl is-enabled "$1" 2>/dev/null | grep -q "^enabled$"
}

svc_is_active() {
    systemctl is-active "$1" 2>/dev/null | grep -q "^active$"
}

print_service_status() {
    local svc="$1"
    local enabled_label active_label

    if svc_is_enabled "$svc"; then
        enabled_label="${GREEN}enabled${NC}"
    else
        enabled_label="${RED}disabled${NC}"
    fi

    if svc_is_active "$svc"; then
        active_label="${GREEN}running${NC}"
    else
        active_label="${YELLOW}stopped${NC}"
    fi

    printf "  %-36s enabled=%-18b active=%b\n" \
        "$svc" "$enabled_label" "$active_label"
}

# ── Commands ──────────────────────────────────────────────────────────────────
cmd_enable() {
    require_root enable
    step "Enabling BigBrother services for auto-start..."

    for svc in "${SERVICES[@]}"; do
        # Check the unit file exists before attempting to enable
        if ! systemctl cat "$svc" &>/dev/null; then
            warn "$svc unit file not found -- skipping (run setup.sh first?)"
            continue
        fi

        info "Enabling $svc..."
        systemctl enable "$svc" 2>&1 || warn "  enable failed for $svc"

        info "Starting $svc..."
        systemctl start "$svc" 2>&1 || warn "  start failed for $svc (check: journalctl -u $svc)"
    done

    echo ""
    step "Post-enable status"
    for svc in "${SERVICES[@]}"; do
        print_service_status "$svc"
    done

    echo ""
    info "BigBrother will start automatically on next boot"
}

cmd_disable() {
    require_root disable
    step "Disabling BigBrother services..."

    for svc in "${SERVICES[@]}"; do
        if ! systemctl cat "$svc" &>/dev/null; then
            warn "$svc unit file not found -- skipping"
            continue
        fi

        info "Stopping $svc..."
        systemctl stop "$svc" 2>&1 || warn "  stop failed for $svc (may already be stopped)"

        info "Disabling $svc..."
        systemctl disable "$svc" 2>&1 || warn "  disable failed for $svc"
    done

    echo ""
    step "Post-disable status"
    for svc in "${SERVICES[@]}"; do
        print_service_status "$svc"
    done

    echo ""
    info "BigBrother will NOT start automatically on next boot"
}

cmd_status() {
    step "BigBrother service status"
    echo ""
    for svc in "${SERVICES[@]}"; do
        print_service_status "$svc"
    done
    echo ""

    # Summary line
    local enabled_count=0
    local running_count=0
    for svc in "${SERVICES[@]}"; do
        svc_is_enabled "$svc" && ((enabled_count++)) || true
        svc_is_active  "$svc" && ((running_count++)) || true
    done

    local total=${#SERVICES[@]}
    if [[ $enabled_count -eq $total ]]; then
        info "Auto-start: ${GREEN}ON${NC} (${enabled_count}/${total} enabled)"
    elif [[ $enabled_count -eq 0 ]]; then
        info "Auto-start: ${RED}OFF${NC} (${enabled_count}/${total} enabled)"
    else
        warn "Auto-start: partial (${enabled_count}/${total} enabled)"
    fi

    if [[ $running_count -eq $total ]]; then
        info "Running:    ${GREEN}YES${NC} (${running_count}/${total} active)"
    elif [[ $running_count -eq 0 ]]; then
        info "Running:    ${RED}NO${NC}  (${running_count}/${total} active)"
    else
        warn "Running:    partial (${running_count}/${total} active)"
    fi
}

# ── Main ─────────────────────────────────────────────────────────────────────
[[ $# -ge 1 ]] || usage

case "$1" in
    enable)   cmd_enable  ;;
    disable)  cmd_disable ;;
    status)   cmd_status  ;;
    -h|--help) usage ;;
    *) error "Unknown command: $1"; usage ;;
esac
