#!/usr/bin/env bash

set -uo pipefail

if [[ $EUID -ne 0 ]]; then
    echo "ERROR: This script must be run as root."
    exit 1
fi

echo "Searching for installed Cesbo Astra systemd services ..."
echo

declare -A ALL_UNITS=()
ASTRA_UNITS=()

# Collect installed service unit files
while read -r UNIT _; do
    [[ "$UNIT" == *.service ]] || continue
    ALL_UNITS["$UNIT"]=1
done < <(
    systemctl list-unit-files \
        --type=service \
        --all \
        --no-legend \
        --no-pager 2>/dev/null
)

# Additionally collect currently loaded or previously started services
while read -r UNIT; do
    [[ "$UNIT" == *.service ]] || continue
    ALL_UNITS["$UNIT"]=1
done < <(
    systemctl list-units \
        --type=service \
        --all \
        --no-legend \
        --no-pager 2>/dev/null |
    awk '{print $1}'
)

# Check which services actually belong to Cesbo Astra
for UNIT in "${!ALL_UNITS[@]}"; do
    # Skip template units such as astra@.service.
    # Actual instances such as astra@1.service are included.
    [[ "$UNIT" == *@.service ]] && continue

    UNIT_NAME_LOWER="${UNIT,,}"

    UNIT_CONTENT="$(
        systemctl cat "$UNIT" 2>/dev/null || true
    )"

    EXEC_START="$(
        systemctl show "$UNIT" \
            --property=ExecStart \
            --value 2>/dev/null || true
    )"

    if [[ "$UNIT_NAME_LOWER" == *astra* ]] ||
       grep -Eiq \
           'cesbo|(^|[=/[:space:]])astra([[:space:]]|$)' \
           <<< "${UNIT_CONTENT} ${EXEC_START}"; then

        ASTRA_UNITS+=("$UNIT")
    fi
done

if [[ ${#ASTRA_UNITS[@]} -eq 0 ]]; then
    echo "No Cesbo Astra systemd services were found."
    exit 0
fi

# Sort the service list alphabetically
mapfile -t ASTRA_UNITS < <(
    printf '%s\n' "${ASTRA_UNITS[@]}" | sort -u
)

echo "Found Astra services:"
printf '  - %s\n' "${ASTRA_UNITS[@]}"
echo

ERRORS=0

for UNIT in "${ASTRA_UNITS[@]}"; do
    echo "========================================"
    echo "Processing: $UNIT"
    echo "========================================"

    ACTIVE_BEFORE="$(systemctl is-active "$UNIT" 2>/dev/null || true)"
    ENABLED_BEFORE="$(systemctl is-enabled "$UNIT" 2>/dev/null || true)"

    echo "Status before:     ${ACTIVE_BEFORE:-unknown}"
    echo "Autostart before:  ${ENABLED_BEFORE:-unknown}"

    echo "Stopping $UNIT ..."

    if ! systemctl stop "$UNIT"; then
        echo "WARNING: $UNIT could not be stopped cleanly."
        ERRORS=$((ERRORS + 1))
    fi

    echo "Disabling autostart for $UNIT ..."

    # For already disabled or static units, systemctl disable may return
    # a non-zero exit code. The final status is checked separately below.
    systemctl disable "$UNIT" 2>/dev/null || true
    systemctl reset-failed "$UNIT" 2>/dev/null || true

    ACTIVE_AFTER="$(systemctl is-active "$UNIT" 2>/dev/null || true)"
    ENABLED_AFTER="$(systemctl is-enabled "$UNIT" 2>/dev/null || true)"

    echo "Status after:      ${ACTIVE_AFTER:-unknown}"
    echo "Autostart after:   ${ENABLED_AFTER:-unknown}"

    if [[ "$ACTIVE_AFTER" == "active" || "$ACTIVE_AFTER" == "activating" ]]; then
        echo "ERROR: $UNIT is still running."
        ERRORS=$((ERRORS + 1))
    else
        echo "OK: $UNIT has been stopped."
    fi

    case "$ENABLED_AFTER" in
        disabled|static|indirect|masked|not-found)
            echo "OK: $UNIT will not start automatically through the regular systemd autostart mechanism."
            ;;
        *)
            echo "WARNING: Unexpected autostart status: $ENABLED_AFTER"
            ERRORS=$((ERRORS + 1))
            ;;
    esac

    echo
done

echo "========================================"

if [[ $ERRORS -eq 0 ]]; then
    echo "All Cesbo Astra instances have been stopped and disabled."
    exit 0
else
    echo "Operation completed with $ERRORS warning(s) or error(s)."
    exit 1
fi
