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

if ! getent passwd suricatavel > /dev/null; then
    useradd -ms /bin/bash -d /var/opt/suricatavel-agent suricatavel
fi

#echo "Creating/updating storage directories..."
mkdir -p /var/opt/suricatavel-agent/storage/logs /var/opt/suricatavel-agent/storage/app /var/opt/suricatavel-agent/storage/framework/sessions /var/opt/suricatavel-agent/storage/framework/views /var/opt/suricatavel-agent/storage/framework/cache /var/opt/suricatavel-agent/storage/suricata /var/opt/suricatavel-agent/storage/ssh_keys
touch /var/opt/suricatavel-agent/database/database.sqlite
chown -R suricatavel:suricatavel /var/opt/suricatavel-agent/storage
chmod -R 775 /var/opt/suricatavel-agent/storage # More permissive for Laravel logs/cache

#echo "Setting application permissions..."
chown -R suricatavel:suricatavel /var/opt/suricatavel-agent
find /var/opt/suricatavel-agent -type f -exec chmod 0644 {} \;
find /var/opt/suricatavel-agent -type d -exec chmod 2755 {} \; # Directories need execute
# Specific Laravel writable directories
chmod -R ug+rwx /var/opt/suricatavel-agent/storage /var/opt/suricatavel-agent/bootstrap/cache


if [ ! -f /var/opt/suricatavel-agent/.env ]; then
    if [ -f /var/opt/suricatavel-agent/.env.prod ]; then
        #echo "Copying .env.prod to .env..."
        cp /var/opt/suricatavel-agent/.env.prod /var/opt/suricatavel-agent/.env
        chown suricatavel:suricatavel /var/opt/suricatavel-agent/.env
        #echo "Generating application key..."
        su - suricatavel -s /bin/bash -c "cd /var/opt/suricatavel-agent && php artisan key:generate" || echo "Warning: php artisan key:generate failed"
        #echo "Running database migrations..."
        su - suricatavel -s /bin/bash -c "cd /var/opt/suricatavel-agent && php artisan migrate --force" || echo "Warning: php artisan migrate --force failed"
    else
        echo "WARNING: No .env.prod found. Please configure .env manually and run migrations."
    fi
fi

if is_systemd_agent_active; then
    # Manage suricatavel-agent via native systemd service
    systemctl restart suricatavel-agent.service >/dev/null 2>&1 || echo "Warning: systemctl restart suricatavel-agent.service failed."
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

# 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