#!/bin/sh
set -e

is_systemd_agent_active() {
    if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
        if systemctl is-active --quiet suricatavel-agent.service 2>/dev/null; then
            return 0
        fi
    fi
    return 1
}

is_supervisor_active() {
    # Check via systemd if systemd is running as PID 1
    if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
        if systemctl is-active --quiet supervisor.service 2>/dev/null || \
           systemctl is-active --quiet supervisord.service 2>/dev/null; then
            return 0
        fi
    fi

    # Fallback to service command
    if command -v service >/dev/null 2>&1; then
        if service supervisor status >/dev/null 2>&1 || \
           service supervisord status >/dev/null 2>&1; then
            return 0
        fi
    fi

    # Fallback checking daemon PID via supervisorctl
    if command -v supervisorctl >/dev/null 2>&1; then
        if supervisorctl pid >/dev/null 2>&1; then
            return 0
        fi
    fi

    return 1
}

try_start_supervisor() {
    if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
        systemctl start supervisor.service 2>/dev/null || \
        systemctl start supervisord.service 2>/dev/null || true
    elif command -v service >/dev/null 2>&1; then
        service supervisor start 2>/dev/null || \
        service supervisord start 2>/dev/null || true
    elif [ -x /etc/init.d/supervisor ]; then
        /etc/init.d/supervisor start 2>/dev/null || true
    elif [ -x /etc/init.d/supervisord ]; then
        /etc/init.d/supervisord start 2>/dev/null || true
    fi
}

AGENT_DIR=/var/opt/suricatavel-agent
MANAGER_FILE=/etc/suricatavel-agent/service-manager

# PHP of the agent only ever runs as the service user.
as_agent() {
    (cd "$AGENT_DIR" && runuser -u suricatavel -- php artisan "$@")
}

if ! getent passwd suricatavel > /dev/null; then
    useradd --system --no-create-home --home-dir "$AGENT_DIR" --shell /usr/sbin/nologin suricatavel
else
    usermod --shell /usr/sbin/nologin suricatavel
fi

# The code stays as dpkg installed it: owned by root and read-only for the agent,
# so not even a compromised agent can change what it runs. The agent writes only
# its storage, its SQLite database and its .env.
# Earlier versions gave the whole tree to the service user: take it back first.
chown -R root:root "$AGENT_DIR"
find "$AGENT_DIR" -type d -exec chmod u-s,g-s,u=rwx,go=rx {} +
chmod -R go-w "$AGENT_DIR"
mkdir -p "$AGENT_DIR/storage/logs" "$AGENT_DIR/storage/app/pki" "$AGENT_DIR/storage/framework/sessions" \
    "$AGENT_DIR/storage/framework/views" "$AGENT_DIR/storage/framework/cache" "$AGENT_DIR/database"
touch "$AGENT_DIR/database/database.sqlite"
for writable in "$AGENT_DIR/storage" "$AGENT_DIR/database"; do
    chown -R suricatavel:suricatavel "$writable"
    find "$writable" -type d -exec chmod u-s,g-s,u=rwx,g=rx,o= {} +
    find "$writable" -type f -exec chmod 0640 {} +
done
# The mTLS private key and its directory.
chmod u-s,g-s,u=rwx,go= "$AGENT_DIR/storage/app/pki"
find "$AGENT_DIR/storage/app/pki" -type f -name '*.key' -exec chmod 0600 {} +

if [ ! -f "$AGENT_DIR/.env" ] && [ -f "$AGENT_DIR/.env.prod" ]; then
    cp "$AGENT_DIR/.env.prod" "$AGENT_DIR/.env"
    chown suricatavel:suricatavel "$AGENT_DIR/.env"
    chmod 0600 "$AGENT_DIR/.env"
    as_agent key:generate --force || echo "Warning: php artisan key:generate failed"
    as_agent migrate --force || echo "Warning: php artisan migrate --force failed"
elif [ -f "$AGENT_DIR/.env" ]; then
    chown suricatavel:suricatavel "$AGENT_DIR/.env"
    chmod 0600 "$AGENT_DIR/.env"
else
    echo "WARNING: No .env.prod found. Please configure .env manually and run migrations."
fi

# The service manager the CLI drives (see support/bin/suricatavel-agent-helper);
# Ansible writes its own choice.
if [ ! -f "$MANAGER_FILE" ]; then
    mkdir -p "$(dirname "$MANAGER_FILE")"
    if is_systemd_agent_active || { command -v systemctl >/dev/null 2>&1 && systemctl is-enabled --quiet suricatavel-agent.service 2>/dev/null; }; then
        echo systemd > "$MANAGER_FILE"
    else
        echo supervisor > "$MANAGER_FILE"
    fi
    chmod 0644 "$MANAGER_FILE"
fi

MANAGER=$(sed -n '1{s/[[:space:]]//g;p;}' "$MANAGER_FILE")
SUPERVISOR_PROGRAM=/etc/supervisor/conf.d/suricatavel-agent.conf

# One manager runs the agent: a supervisor program next to the systemd unit would start it twice.
# Earlier versions shipped the program as a conffile; it is now installed only for supervisor.
if [ "$MANAGER" = supervisor ]; then
    mkdir -p "$(dirname "$SUPERVISOR_PROGRAM")"
    install -m 0644 "$AGENT_DIR/support/supervisor/suricatavel-agent.conf" "$SUPERVISOR_PROGRAM"
else
    rm -f "$SUPERVISOR_PROGRAM"
fi

if [ "$MANAGER" != supervisor ]; then
    if is_supervisor_active; then
        # Drops a program left by an earlier version.
        supervisorctl reread >/dev/null 2>&1 || true
        supervisorctl update >/dev/null 2>&1 || true
    fi
    if [ "$MANAGER" = systemd ] && command -v systemctl >/dev/null 2>&1; then
        systemctl try-restart suricatavel-agent.service >/dev/null 2>&1 || echo "Warning: systemctl try-restart suricatavel-agent.service failed."
    fi
else
    # Try starting supervisor if installed but not currently active
    if ! is_supervisor_active && command -v supervisorctl >/dev/null 2>&1; then
        try_start_supervisor
    fi

    if is_supervisor_active; then
        #echo "Reloading supervisor configuration if supervisor is running"
        supervisorctl reread >/dev/null 2>&1 || echo "Warning: supervisorctl reread failed. Supervisor might not be running."
        supervisorctl update >/dev/null 2>&1 || echo "Warning: supervisorctl update failed. Supervisor might not be running."
        #echo "Attempting to start suricatavel-agent service via supervisor"
        supervisorctl start suricatavel-agent >/dev/null 2>&1 || supervisorctl start suricatavel-agent:* >/dev/null 2>&1 || echo "Warning: supervisorctl start failed. Supervisor might not be running or service already started/failed."
    elif command -v supervisorctl >/dev/null 2>&1; then
        echo "WARNING: supervisorctl is installed, but the supervisor service is not running. Please start the supervisor service (e.g. 'systemctl start supervisor' or 'service supervisor start') to manage suricatavel-agent automatically."
    else
        echo "WARNING: supervisorctl command not found and no active suricatavel-agent systemd service detected. Cannot manage suricatavel-agent service automatically."
    fi
fi

# Suricatavel Agent CLI (the package ships /usr/bin/suricatavel-agent).
chmod 0755 "$AGENT_DIR/support/bin/suricatavel-agent" "$AGENT_DIR/support/bin/suricatavel-agent-helper"
rm -f /usr/local/bin/suricatavel-agent

# Add cron job for Laravel scheduler
CRON_USER="suricatavel"
CRON_CMD="cd /var/opt/suricatavel-agent && php artisan schedule:run >> /dev/null 2>&1"
if crontab -u "$CRON_USER" -l 2>/dev/null | grep -Fxq "* * * * * $CRON_CMD"; then
    : # echo "Scheduler cron job already exists for user $CRON_USER."
else
    (crontab -u "$CRON_USER" -l 2>/dev/null; echo "* * * * * $CRON_CMD") | crontab -u "$CRON_USER" -
    # echo "Scheduler cron job added for user $CRON_USER."
fi

#DEBHELPER#

exit 0