#!/bin/sh
# postinst for madcat-caddy
#
# Handles:
#   - Fresh install (no prior caddy)
#   - Upgrade from stock caddy with masked service
#   - Upgrade from previous madcat-caddy

set -e

UNIT_PATH="/usr/lib/systemd/system/caddy.service"

# Create caddy user/group if they don't exist
if ! getent group caddy >/dev/null 2>&1; then
    groupadd --system caddy
fi

if ! getent passwd caddy >/dev/null 2>&1; then
    useradd --system --gid caddy --create-home --home-dir /var/lib/caddy --shell /usr/sbin/nologin caddy
fi

# Create config and data directories
mkdir -p /etc/caddy
mkdir -p /var/lib/caddy/.config/caddy
mkdir -p /var/lib/caddy/.local/share/caddy
chown -R caddy:caddy /var/lib/caddy

# Stop caddy-api.service if it exists (leftover from stock caddy)
if [ -d /run/systemd/system ]; then
    systemctl stop caddy-api.service 2>/dev/null || true
fi

# Handle systemd service setup
if [ -d /run/systemd/system ]; then
    # If the unit file is missing (removed during package transition) or is a
    # dangling symlink (masked unit pointing to /dev/null), recreate it.
    if [ ! -f "$UNIT_PATH" ] || [ -L "$UNIT_PATH" ]; then
        # Unmask first — removes the /dev/null symlink if masked
        systemctl unmask caddy.service 2>/dev/null || true

        # If still missing after unmask, recreate from our embedded copy
        if [ ! -f "$UNIT_PATH" ]; then
            mkdir -p "$(dirname "$UNIT_PATH")"
            cat > "$UNIT_PATH" << 'UNIT'
[Unit]
Description=Caddy web server (madcat-caddy)
Documentation=https://caddyserver.com/docs/
After=network.target network-online.target
Requires=network-online.target

[Service]
Type=notify
User=caddy
Group=caddy
ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile
ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true

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

    # Reload systemd to pick up the unit file (new or recreated)
    systemctl daemon-reload

    # Unmask again after reload in case it was masked in systemd's state
    systemctl unmask caddy.service 2>/dev/null || true

    # Enable and start
    systemctl enable caddy.service
    systemctl start caddy.service || true
fi
