#!/bin/sh
#
# FreeBSD/OPNsense pkg post-install script for suricatavel-agent
#

# Use fixed prefix to avoid surprises during pkg install/upgrade
PKG_PREFIX="/usr/local"
INSTALL_DIR="${PKG_PREFIX}/suricatavel-agent"
PHP_BIN="${PKG_PREFIX}/bin/php"
PHP_INI="${PKG_PREFIX}/etc/php.ini"
REPO_URL="https://repository.suricatavel.org/freebsd"
FINGERPRINT_DIR="${PKG_PREFIX}/etc/pkg/fingerprints/suricatavel"

IS_UPGRADE="false"
if [ "${PKG_UPGRADE}" = "true" ] || [ -f "${INSTALL_DIR}/.env" ]; then
    IS_UPGRADE="true"
fi

mkdir -p "${FINGERPRINT_DIR}/trusted"
mkdir -p "${FINGERPRINT_DIR}/revoked"

if [ ! -f "${FINGERPRINT_DIR}/trusted/suricatavel" ]; then
    # echo "==> Downloading repository fingerprint..."
    fetch -T 10 -o "${FINGERPRINT_DIR}/trusted/suricatavel" \
        "${REPO_URL}/fingerprints/trusted/suricatavel" 2>/dev/null || \
        echo "Warning: Could not download fingerprint. Repository signature verification may fail."
fi

# Setup repository configuration
if [ ! -f "${PKG_PREFIX}/etc/pkg/repos/suricatavel.conf" ]; then
    mkdir -p "${PKG_PREFIX}/etc/pkg/repos"
    if [ -f "${INSTALL_DIR}/support/freebsd/suricatavel.conf" ]; then
        cp "${INSTALL_DIR}/support/freebsd/suricatavel.conf" "${PKG_PREFIX}/etc/pkg/repos/"
        # echo "==> Repository configuration installed to ${PKG_PREFIX}/etc/pkg/repos/suricatavel.conf"
    fi
fi

if ! pw usershow suricatavel >/dev/null 2>&1; then
    pw useradd -n suricatavel -d /nonexistent -s /usr/sbin/nologin -c "Suricatavel Agent"
fi
mkdir -p "${INSTALL_DIR}/storage/logs"
mkdir -p "${INSTALL_DIR}/storage/app"
mkdir -p "${INSTALL_DIR}/storage/framework/sessions"
mkdir -p "${INSTALL_DIR}/storage/framework/views"
mkdir -p "${INSTALL_DIR}/storage/framework/cache"
mkdir -p "${INSTALL_DIR}/storage/suricata"
mkdir -p "${INSTALL_DIR}/database"
touch "${INSTALL_DIR}/database/database.sqlite"

chown -R suricatavel:suricatavel "${INSTALL_DIR}"
chmod -R 755 "${INSTALL_DIR}"
chmod -R 775 "${INSTALL_DIR}/storage"
if [ -f "${INSTALL_DIR}/.env" ]; then
    chmod 640 "${INSTALL_DIR}/.env"
    chown suricatavel:suricatavel "${INSTALL_DIR}/.env"
fi

# Enable FFI in php.ini if not already enabled
if [ -f "${PHP_INI}" ]; then
    if ! grep -q "^ffi.enable=true" "${PHP_INI}"; then
        if grep -q "ffi.enable" "${PHP_INI}"; then
            sed -i '' 's/^;*ffi.enable.*/ffi.enable=true/' "${PHP_INI}"
        else
            echo "" >> "${PHP_INI}"
            echo "; Suricatavel Agent - Enable FFI for kqueue file monitoring" >> "${PHP_INI}"
            echo "ffi.enable=true" >> "${PHP_INI}"
        fi
    fi
fi

CRON_CMD="cd ${INSTALL_DIR} && ${PHP_BIN} artisan schedule:run >> /dev/null 2>&1"
if ! grep -Fq "${CRON_CMD}" /etc/crontab; then
    echo "*	*	*	*	*	suricatavel	${CRON_CMD}" >> /etc/crontab
fi

cat > "${PKG_PREFIX}/bin/suricatavel-agent-start" << 'WRAPPEREOF'
#!/bin/sh
export HOME=/usr/local/suricatavel-agent
export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
cd /usr/local/suricatavel-agent
exec /usr/local/bin/php artisan agent:start
WRAPPEREOF
chmod +x "${PKG_PREFIX}/bin/suricatavel-agent-start"

cat > "${PKG_PREFIX}/etc/rc.d/suricatavel_agent" << 'RCEOF'
#!/bin/sh
#
# PROVIDE: suricatavel_agent
# REQUIRE: LOGIN NETWORKING php
# KEYWORD: shutdown
#
# Add the following line to /etc/rc.conf to enable suricatavel_agent:
#   suricatavel_agent_enable="YES"

. /etc/rc.subr

name="suricatavel_agent"
rcvar="${name}_enable"
pidfile="/var/run/${name}.pid"

load_rc_config $name

: ${suricatavel_agent_enable:="NO"}
: ${suricatavel_agent_user:="root"}
: ${suricatavel_agent_dir:="/usr/local/suricatavel-agent"}

procname="/usr/local/bin/php"
start_cmd="${name}_start"

suricatavel_agent_start()
{
    if [ ! -f "${suricatavel_agent_dir}/.env" ]; then
        echo "Error: ${suricatavel_agent_dir}/.env not found"
        echo "Please configure the agent first"
        return 1
    fi

    echo "Starting ${name}..."
    # critical: use limits -C daemon to ensure login class restrictions don't kill the environment
    /usr/bin/limits -C daemon /usr/sbin/daemon -p ${pidfile} -f -S -T ${name} /usr/local/bin/suricatavel-agent-start
}

run_rc_command "$1"
RCEOF

chmod +x "${PKG_PREFIX}/etc/rc.d/suricatavel_agent"

if [ ! -f "${INSTALL_DIR}/.env" ]; then
    if [ -f "${INSTALL_DIR}/.env.prod" ]; then
        cp "${INSTALL_DIR}/.env.prod" "${INSTALL_DIR}/.env"
        chown suricatavel:suricatavel "${INSTALL_DIR}/.env"
        chmod 640 "${INSTALL_DIR}/.env"
        
        # Generate key only when creating new .env
        if [ -x "${PHP_BIN}" ]; then
            cd "${INSTALL_DIR}"
            su -m suricatavel -c "${PHP_BIN} artisan key:generate --force" || echo "Warning: key:generate failed"
        fi
    else
        echo "WARNING: No .env.prod found. Please configure .env manually."
    fi
fi

if [ -x "${PHP_BIN}" ] && [ -f "${INSTALL_DIR}/.env" ]; then
    cd "${INSTALL_DIR}"
    su -m suricatavel -c "${PHP_BIN} artisan migrate --force" || echo "Warning: migrate failed"
fi

if [ "$IS_UPGRADE" = "false" ]; then
    # New installation: enable service and show message
    sysrc suricatavel_agent_enable=YES
    
    cat << 'EOF'

========================================
Suricatavel Agent installed successfully
========================================

IMPORTANT: Configure the agent before starting:
  vi /usr/local/suricatavel-agent/.env

Set KAFKA_BROKERS to your Kafka server(s), then start:
  service suricatavel_agent start
EOF
else
    # Upgrade: clear caches and restart if running
    if [ -x "${PHP_BIN}" ] && [ -f "${INSTALL_DIR}/.env" ]; then
        cd "${INSTALL_DIR}"
        su -m suricatavel -c "${PHP_BIN} artisan config:clear" || echo "Warning: config:clear failed"
        su -m suricatavel -c "${PHP_BIN} artisan cache:clear" || echo "Warning: cache:clear failed"
    fi
    
    if service suricatavel_agent status >/dev/null 2>&1; then
        service suricatavel_agent restart
    fi
fi
