#!/bin/bash
# ============================================================
# cockpit.sh — Cockpit web-based server management UI
# ============================================================
# Installs Cockpit, a browser-based administration interface
# that provides real-time system monitoring, journal viewing,
# storage management, and more — all accessible at
# https://localhost:9090.
#
# Packages installed:
#   cockpit         — core web UI and API layer
#   cockpit-pcp     — Performance Co-Pilot integration
#                     (enables historical metrics charts)
#   pcp             — Performance Co-Pilot daemon (required by cockpit-pcp)
#   cockpit-machines — virtual machine management via libvirt
#   cockpit-podman  — container management via Podman API
#   cockpit-navigator — file browser add-on for Cockpit
#
# The core and pcp packages come from the official Arch repos;
# the plugin packages (machines, podman, navigator) are
# AUR-only.
#
# This is an optional module because Cockpit is primarily
# useful on servers or development machines; it is not needed
# on a standard desktop.
# ============================================================

set -euo pipefail
# Load shared logging helpers from the dotfiles lib
source "$(dirname "${BASH_SOURCE[0]}")/../../lib/logging.sh"

# ── Core Cockpit packages (official repos) ────────────────────────────────────
# cockpit     : the main web server component and administration framework
# cockpit-pcp : bridge between Cockpit and PCP; enables the metrics history page
# pcp         : Performance Co-Pilot — collects and archives system performance
#               data (CPU, memory, disk I/O, etc.) that cockpit-pcp then displays
log "Installing Cockpit (core + official plugins)..."
sudo pacman -S --noconfirm --needed \
    cockpit \
    cockpit-pcp \
    pcp

# ── Cockpit plugin extensions (AUR) ──────────────────────────────────────────
# cockpit-machines  : manage QEMU/KVM virtual machines directly from the web UI
# cockpit-podman    : manage rootless and rootful Podman containers
# cockpit-navigator : graphical file manager widget inside Cockpit
log "Installing Cockpit AUR plugins (machines, podman, navigator)..."
yay -S --answerdiff None --answerclean All --noconfirm \
    cockpit-machines \
    cockpit-podman \
    cockpit-navigator

# ── Enable Cockpit socket activation ─────────────────────────────────────────
# Cockpit uses systemd socket activation: the cockpit.socket unit listens on
# port 9090 and starts cockpit.service only when an incoming connection arrives.
# This is more efficient than keeping the full web server running at all times.
log "Enabling Cockpit socket..."
enable_service cockpit.socket

log "Cockpit enabled. Web UI available at https://localhost:9090"
