#!/bin/sh
#
# postinstall — macOS installer post-flight script for unicornscan
#
# Runs after the package payload has been written to disk.  This script:
#   1. Loads the ChmodBPF LaunchDaemon (sets /dev/bpf* permissions at boot)
#   2. Creates the 'unicornscan' group (for BPF device access)
#   3. Adds the installing user to that group
#
# This script is executed by the macOS Installer framework as root.
# Exit 0 = success, non-zero = report error (files are already installed).
#

set -e

# The macOS Installer sandbox has a minimal PATH (/usr/bin:/bin:/usr/sbin:/sbin).
# Docker, Homebrew, and our own binaries live outside that, so we extend PATH
# to include the locations where they are actually installed.
export PATH="/opt/homebrew/bin:/usr/local/bin:/opt/homebrew/sbin:/usr/local/sbin:$PATH"

SCRIPT_NAME="$(basename "$0")"
BPF_GROUP="unicornscan"
PLIST_PATH="/Library/LaunchDaemons/org.unicornscan.ChmodBPF.plist"
CHMODBPF_PATH="/usr/local/bin/ChmodBPF"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

log_info() {
    logger -t "unicornscan-postinstall" "$1" 2>/dev/null || true
    echo "${SCRIPT_NAME}: $1"
}

log_warn() {
    logger -p user.warning -t "unicornscan-postinstall" "$1" 2>/dev/null || true
    echo "${SCRIPT_NAME}: WARNING: $1" >&2
}

log_error() {
    logger -p user.err -t "unicornscan-postinstall" "$1" 2>/dev/null || true
    echo "${SCRIPT_NAME}: ERROR: $1" >&2
}

# ---------------------------------------------------------------------------
# Step 1: Load the ChmodBPF LaunchDaemon
# ---------------------------------------------------------------------------
# If a previous version is already loaded, unload it first so we pick up
# any changes to the plist or the ChmodBPF script itself.

log_info "Configuring ChmodBPF LaunchDaemon..."

if [ ! -f "${PLIST_PATH}" ]; then
    log_warn "LaunchDaemon plist not found at ${PLIST_PATH}."
    log_warn "BPF device permissions will not be set automatically at boot."
    log_warn "You can install it manually from the macos/ directory."
else
    # Ensure the ChmodBPF script is executable.
    if [ -f "${CHMODBPF_PATH}" ]; then
        chmod 755 "${CHMODBPF_PATH}"
        chown root:wheel "${CHMODBPF_PATH}"
    else
        log_warn "ChmodBPF script not found at ${CHMODBPF_PATH}."
    fi

    # Ensure correct ownership on the plist.
    chown root:wheel "${PLIST_PATH}"
    chmod 644 "${PLIST_PATH}"

    # Unload if already present (ignore errors — may not be loaded).
    if launchctl list org.unicornscan.ChmodBPF >/dev/null 2>&1; then
        log_info "Unloading existing ChmodBPF daemon..."
        launchctl unload "${PLIST_PATH}" 2>/dev/null || true
    fi

    # Load the daemon.  RunAtLoad=true in the plist means ChmodBPF will
    # execute immediately, setting /dev/bpf* permissions right now.
    if launchctl load "${PLIST_PATH}"; then
        log_info "ChmodBPF LaunchDaemon loaded successfully."
        log_info "BPF device permissions will be set at every boot."
    else
        log_warn "Failed to load ChmodBPF LaunchDaemon."
        log_warn "You may need to load it manually:"
        log_warn "  sudo launchctl load ${PLIST_PATH}"
    fi
fi

# ---------------------------------------------------------------------------
# Step 2: Create the 'unicornscan' group
# ---------------------------------------------------------------------------
# The ChmodBPF script also creates the group, but we do it here too for
# the case where the daemon did not load successfully.

log_info "Checking for '${BPF_GROUP}' group..."

if dseditgroup -o read "${BPF_GROUP}" >/dev/null 2>&1; then
    log_info "Group '${BPF_GROUP}' already exists."
else
    log_info "Creating group '${BPF_GROUP}'..."
    if dseditgroup -o create -r "unicornscan BPF access" "${BPF_GROUP}"; then
        log_info "Group '${BPF_GROUP}' created."
    else
        log_error "Failed to create group '${BPF_GROUP}'."
        log_error "You can create it manually with:"
        log_error "  sudo dseditgroup -o create -r 'unicornscan BPF access' ${BPF_GROUP}"
        # Do not exit — the package files are already installed.
    fi
fi

# ---------------------------------------------------------------------------
# Step 3: Add the installing user to the unicornscan group
# ---------------------------------------------------------------------------
# Determine who ran the installer.  The macOS Installer passes the
# installing user's name in $USER or we can fall back to the console user.

REAL_USER="${USER:-}"
if [ -z "${REAL_USER}" ] || [ "${REAL_USER}" = "root" ]; then
    REAL_USER="$(stat -f '%Su' /dev/console 2>/dev/null || true)"
fi

if [ -z "${REAL_USER}" ] || [ "${REAL_USER}" = "root" ]; then
    log_warn "Could not determine a non-root user to add to '${BPF_GROUP}'."
    log_warn "Add users manually with:"
    log_warn "  sudo dseditgroup -o edit -a USERNAME -t user ${BPF_GROUP}"
else
    if dseditgroup -o checkmember -m "${REAL_USER}" "${BPF_GROUP}" >/dev/null 2>&1; then
        log_info "User '${REAL_USER}' is already a member of '${BPF_GROUP}'."
    else
        log_info "Adding user '${REAL_USER}' to group '${BPF_GROUP}'..."
        if dseditgroup -o edit -a "${REAL_USER}" -t user "${BPF_GROUP}"; then
            log_info "User '${REAL_USER}' added to '${BPF_GROUP}'."
        else
            log_error "Failed to add '${REAL_USER}' to '${BPF_GROUP}'."
            log_error "Add manually with:"
            log_error "  sudo dseditgroup -o edit -a ${REAL_USER} -t user ${BPF_GROUP}"
        fi
    fi
fi

# ---------------------------------------------------------------------------
# Step 4: Fix config file permissions
# ---------------------------------------------------------------------------
# The installer copies files as root.  Some config files in the staging
# area may have restrictive permissions from the build.  Ensure all
# config files under /usr/local/etc/unicornscan/ are world-readable
# so unicornscan can parse them when running as a non-root user.

CONFDIR="/usr/local/etc/unicornscan"
if [ -d "${CONFDIR}" ]; then
    chmod 644 "${CONFDIR}"/*.conf "${CONFDIR}"/*.txt 2>/dev/null || true
    # modules.conf also needs user write access so unicornscan-alicorn can
    # sync the database password into it.  The actual chown happens in
    # Step 6 AFTER the sed operations (sed -i creates a new root-owned file).
    log_info "Config file permissions set to 644."
fi

# ---------------------------------------------------------------------------
# Step 5: Create the localstatedir for IPC sockets
# ---------------------------------------------------------------------------

VARDIR="/usr/local/var/unicornscan"
if [ ! -d "${VARDIR}" ]; then
    log_info "Creating state directory ${VARDIR}..."
    mkdir -p "${VARDIR}"
    chmod 755 "${VARDIR}"
fi

# ---------------------------------------------------------------------------
# Step 6: Generate database password and configure pgsqldb module
# ---------------------------------------------------------------------------
# Generate a random password for the Alicorn PostgreSQL database and
# pre-configure modules.conf so that `unicornscan -epgsqldb <target>`
# works out of the box after `unicornscan-alicorn start`.  This mirrors
# what the Linux packages do via unicornscan-alicorn's init_env().

ALICORN_VAR="/usr/local/var/unicornscan/alicorn"
ALICORN_ENV="${ALICORN_VAR}/.env"
ALICORN_PWFILE="${ALICORN_VAR}/.db_password"
CONFDIR="/usr/local/etc/unicornscan"

if [ ! -f "${ALICORN_PWFILE}" ]; then
    mkdir -p "${ALICORN_VAR}"

    # Remove orphan Docker volume from a prior install.  The volume's
    # PostgreSQL data has the OLD password baked in (set during initdb);
    # PostgreSQL ignores POSTGRES_PASSWORD on subsequent starts.  Since
    # we have no .db_password file, we cannot recover the old password,
    # so the volume must go.
    if command -v docker >/dev/null 2>&1; then
        if docker volume inspect alicorn_postgres_data >/dev/null 2>&1; then
            log_info "Removing orphan database volume (password unrecoverable)..."
            # Stop any container using the volume first
            docker stop alicorn-postgres 2>/dev/null || true
            docker rm alicorn-postgres 2>/dev/null || true
            docker volume rm alicorn_postgres_data 2>/dev/null || true
        fi
    fi

    DB_PASSWORD="$(LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32)"

    # Write .env for Docker Compose
    cat > "${ALICORN_ENV}" << ENVEOF
# Alicorn Docker Configuration
# Generated by installer on $(date '+%Y-%m-%dT%H:%M:%S%z')
POSTGRES_USER=alicorn
POSTGRES_PASSWORD=${DB_PASSWORD}
POSTGRES_DB=unicornscan
ENVEOF
    chmod 600 "${ALICORN_ENV}"

    # Save password for easy retrieval
    echo "${DB_PASSWORD}" > "${ALICORN_PWFILE}"
    chmod 600 "${ALICORN_PWFILE}"

    # Update modules.conf with the generated password
    if [ -f "${CONFDIR}/modules.conf" ]; then
        sed -i '' "s/password=[^;[:space:]\"]*/password=${DB_PASSWORD}/" "${CONFDIR}/modules.conf"
        log_info "Database password generated and modules.conf updated."
    fi
else
    # Reinstall/upgrade: password file exists but the pkg payload just
    # overwrote modules.conf with the default (password=CHANGE_ME).
    # Re-apply the existing password so -epgsqldb works immediately.
    DB_PASSWORD="$(cat "${ALICORN_PWFILE}")"
    if [ -n "${DB_PASSWORD}" ] && [ -f "${CONFDIR}/modules.conf" ]; then
        sed -i '' "s/password=[^;[:space:]\"]*/password=${DB_PASSWORD}/" "${CONFDIR}/modules.conf"
        log_info "Reinstall: re-applied existing database password to modules.conf."
    else
        log_info "Database password already exists — skipping generation."
    fi
fi

# Restore user ownership after sed -i (which creates a new root-owned file).
# unicornscan-alicorn's sync_modules_conf() needs write access.
if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ]; then
    chown "${REAL_USER}" "${CONFDIR}/modules.conf" 2>/dev/null || true
fi

# ---------------------------------------------------------------------------
# Step 7: Ensure Docker is available
# ---------------------------------------------------------------------------
# Alicorn requires Docker for the PostgreSQL + web UI stack.  If Docker
# is not present, try to install it via Homebrew (Colima + Docker CLI).
# If Homebrew is also absent, tell the user exactly what to do.

DOCKER_AVAILABLE="no"
ALICORN_SCRIPT="/usr/local/bin/unicornscan-alicorn"

if command -v docker >/dev/null 2>&1; then
    log_info "Docker found: $(command -v docker)"
    DOCKER_AVAILABLE="yes"
else
    log_info "Docker not found.  Attempting to install via Homebrew..."
    # Homebrew must run as a non-root user
    if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ] && command -v brew >/dev/null 2>&1; then
        log_info "Installing docker, docker-compose, and colima via Homebrew..."
        su - "${REAL_USER}" -c 'brew install docker docker-compose colima 2>&1' || true
        if command -v docker >/dev/null 2>&1; then
            DOCKER_AVAILABLE="yes"
            log_info "Docker installed successfully via Homebrew."
        else
            log_warn "Homebrew install of Docker did not succeed."
        fi
    elif command -v brew >/dev/null 2>&1; then
        log_warn "Homebrew found but could not determine non-root user for install."
    else
        log_warn "Neither Docker nor Homebrew found."
    fi
fi

if [ "${DOCKER_AVAILABLE}" = "no" ]; then
    log_warn "Docker is required for the Alicorn web UI and database output."
    log_warn "Install Docker manually, then start Alicorn:"
    log_warn ""
    log_warn "  Option 1 - Colima (lightweight, recommended):"
    log_warn "    brew install docker docker-compose colima"
    log_warn "    colima start"
    log_warn "    unicornscan-alicorn start"
    log_warn ""
    log_warn "  Option 2 - Docker Desktop:"
    log_warn "    brew install --cask docker"
    log_warn "    # Open Docker Desktop and wait for it to start"
    log_warn "    unicornscan-alicorn start"
fi

# ---------------------------------------------------------------------------
# Step 8: Start Docker daemon if needed
# ---------------------------------------------------------------------------

if [ "${DOCKER_AVAILABLE}" = "yes" ]; then
    # Check Docker daemon as the real user — the Docker socket may only be
    # accessible from the user's context (Colima, Docker Desktop).
    DOCKER_CHECK="docker info >/dev/null 2>&1"
    if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ]; then
        DOCKER_RUNNING="no"
        su - "${REAL_USER}" -c "${DOCKER_CHECK}" && DOCKER_RUNNING="yes"
    else
        docker info >/dev/null 2>&1 && DOCKER_RUNNING="yes" || DOCKER_RUNNING="no"
    fi

    if [ "${DOCKER_RUNNING}" = "no" ]; then
        log_info "Docker installed but daemon not running."
        if command -v colima >/dev/null 2>&1; then
            log_info "Starting Colima..."
            if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ]; then
                su - "${REAL_USER}" -c 'colima start 2>&1' || true
            else
                colima start 2>&1 || true
            fi
        fi
        # Re-check as user
        if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ]; then
            su - "${REAL_USER}" -c "${DOCKER_CHECK}" || DOCKER_AVAILABLE="no"
        else
            docker info >/dev/null 2>&1 || DOCKER_AVAILABLE="no"
        fi
        if [ "${DOCKER_AVAILABLE}" = "no" ]; then
            log_warn "Docker daemon still not running."
            log_warn "Start it manually, then run: unicornscan-alicorn start"
        fi
    fi
fi

# ---------------------------------------------------------------------------
# Step 9: Start Alicorn web UI
# ---------------------------------------------------------------------------
# Stop any stale containers, then start the full stack so the user can
# immediately scan with -epgsqldb and view results at localhost:31337.

if [ "${DOCKER_AVAILABLE}" = "yes" ] && [ -x "${ALICORN_SCRIPT}" ]; then
    # Ensure the var dir is writable by the installing user (postinstall
    # runs as root, but unicornscan-alicorn needs user write access for
    # Docker Compose .env, logs, etc.)
    if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ]; then
        chown -R "${REAL_USER}" /usr/local/var/unicornscan 2>/dev/null || true
    fi

    # Stop stale containers from a previous install
    for container in alicorn-postgres alicorn-postgrest alicorn-web alicorn-geoip; do
        if docker ps -q --filter "name=${container}" 2>/dev/null | grep -q .; then
            log_info "Stopping stale container: ${container}"
            docker stop "${container}" 2>/dev/null || true
            docker rm "${container}" 2>/dev/null || true
        fi
    done

    log_info "Starting Alicorn web UI..."
    if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ]; then
        su - "${REAL_USER}" -c "${ALICORN_SCRIPT} start 2>&1" || \
            log_warn "Alicorn start failed.  Run manually: unicornscan-alicorn start"
    else
        "${ALICORN_SCRIPT}" start 2>&1 || \
            log_warn "Alicorn start failed.  Run manually: unicornscan-alicorn start"
    fi
fi

# ---------------------------------------------------------------------------
# Step 10: Download free GeoIP databases
# ---------------------------------------------------------------------------
# Download DB-IP Lite databases so GeoIP lookups work out of the box.
# These are free (CC BY 4.0) and require no registration.
# Run in the background so the installer doesn't hang on slow connections.

GEOIP_SCRIPT="/usr/local/bin/unicornscan-geoip-update"
if [ -x "${GEOIP_SCRIPT}" ]; then
    log_info "Downloading free GeoIP databases (background)..."
    "${GEOIP_SCRIPT}" &
    GEOIP_PID=$!
    # Wait up to 30 seconds for the download to complete.
    # If it takes longer, let it finish in the background.
    GEOIP_WAIT=0
    while kill -0 "${GEOIP_PID}" 2>/dev/null && [ "${GEOIP_WAIT}" -lt 30 ]; do
        sleep 1
        GEOIP_WAIT=$((GEOIP_WAIT + 1))
    done
    if kill -0 "${GEOIP_PID}" 2>/dev/null; then
        log_info "GeoIP download still running in background (PID ${GEOIP_PID})."
    else
        GEOIP_RC=0
        wait "${GEOIP_PID}" 2>/dev/null || GEOIP_RC=$?
        if [ "${GEOIP_RC}" -eq 0 ]; then
            log_info "GeoIP databases downloaded successfully."
        else
            log_warn "GeoIP download exited with code ${GEOIP_RC}.  Run manually: sudo unicornscan-geoip-update"
        fi
    fi
else
    log_warn "unicornscan-geoip-update not found.  GeoIP databases not downloaded."
fi

# ---------------------------------------------------------------------------
# Done
# ---------------------------------------------------------------------------

echo ""
echo "=========================================================="
echo "  Unicornscan installation complete."
echo ""
echo "  BPF device permissions have been configured."
echo "  The 'unicornscan' group controls packet-capture access."
echo ""
if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ]; then
echo "  User '${REAL_USER}' has been added to the '${BPF_GROUP}'"
echo "  group.  You MUST log out and log back in (or reboot)"
echo "  for the group membership to take effect."
echo ""
fi
if [ "${DOCKER_AVAILABLE}" = "yes" ]; then
echo "  Alicorn web UI:  http://localhost:31337"
echo "  Scan with DB:    unicornscan -epgsqldb <target>"
echo ""
fi
echo "  Quick start:"
echo "    unicornscan -mT 192.168.1.1:1-1024"
echo ""
echo "  To uninstall: sudo unicornscan-uninstall"
echo "  Full docs:    https://unicornscan.org/docs/getting-started"
echo "=========================================================="
echo ""

exit 0
