#!/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
}

# The code, 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 state, caches and logs; bootstrap/layout.php says where they are.
AGENT_DIR=/usr/share/suricatavel-agent
STATE_DIR=/var/lib/suricatavel-agent
MANAGER_FILE=/etc/suricatavel-agent/service-manager
UNIT=suricatavel-agent.service

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

# Directories of the layout, the .env and the database migrations.
chmod 0755 "$AGENT_DIR"/support/bin/*
"$AGENT_DIR/support/bin/suricatavel-agent-setup"

# The package ships the unit in /usr/lib/systemd/system.
if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
    systemctl daemon-reload >/dev/null 2>&1 || true
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: install the supervisor program only when supervisor is selected.
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
        # Reload supervisor so any stale program file removed above is unloaded.
        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 "$UNIT" >/dev/null 2>&1 || echo "Warning: systemctl try-restart $UNIT 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).
rm -f /usr/local/bin/suricatavel-agent

# Cron job for the Laravel scheduler
CRON_USER="suricatavel"
CRON_LINE="* * * * * cd $AGENT_DIR && php artisan schedule:run >> /dev/null 2>&1"
if ! crontab -u "$CRON_USER" -l 2>/dev/null | grep -Fxq "$CRON_LINE"; then
    (crontab -u "$CRON_USER" -l 2>/dev/null || true; echo "$CRON_LINE") | crontab -u "$CRON_USER" -
fi

#DEBHELPER#

exit 0