#!/usr/bin/sh
#
# Prepares the directories of the installed layout (bootstrap/layout.php: configuration, state, caches and logs
# apart from the code), creates the .env from the template of the package and migrates the database. Run as root
# by the packages after they install the code; safe to run again.

set -eu

PATH=$PATH:/usr/local/bin
SERVICE_USER=suricatavel

script=$(readlink -f "$0" 2>/dev/null || echo "$0")
CODE=$(cd "$(dirname "$script")/../.." && pwd -P)

if [ "$(id -u)" -ne 0 ]; then
    echo 'Error: suricatavel-agent-setup runs as root.' >&2
    exit 1
fi

if [ ! -f "$CODE/bootstrap/layout.php" ]; then
    echo "Error: $CODE/bootstrap/layout.php is missing: this is not a packaged installation." >&2
    exit 1
fi

layout() {
    php -r '$layout = require $argv[1]; echo $layout[$argv[2]];' "$CODE/bootstrap/layout.php" "$1"
}

CONFIG=$(layout config)
STATE=$(layout state)
CACHE=$(layout cache)
LOGS=$(layout logs)
GROUP=$(id -gn "$SERVICE_USER")

# PHP of the agent only ever runs as the service user.
as_agent() {
    if command -v runuser >/dev/null 2>&1; then
        (cd "$CODE" && HOME=$STATE runuser -u "$SERVICE_USER" -- php artisan "$@")
    else
        (cd "$CODE" && HOME=$STATE su -m "$SERVICE_USER" -c "php artisan $*")
    fi
}

install -d -m 0755 "$CONFIG"
for directory in "$STATE" "$STATE/app" "$STATE/framework" "$STATE/framework/cache" "$STATE/framework/sessions" \
    "$CACHE" "$CACHE/views" "$LOGS"; do
    install -d -o "$SERVICE_USER" -g "$GROUP" -m 0750 "$directory"
done
install -d -o "$SERVICE_USER" -g "$GROUP" -m 0700 "$STATE/app/pki"

# The service user owns its state, caches and logs, readable by nobody else; the mTLS key stays private to it.
touch "$STATE/database.sqlite"
chown -R "$SERVICE_USER:$GROUP" "$STATE" "$CACHE" "$LOGS"
for directory in "$STATE" "$CACHE" "$LOGS"; do
    find "$directory" -type f -exec chmod 0640 {} +
done
find "$STATE/app/pki" -type f -name '*.key' -exec chmod 0600 {} +

# Runtime caches (config, routes, events) freeze the .env and the agent cannot remove them (the code is root's):
# the agent runs without them. The package's own manifests (packages.php, services.php) stay.
rm -f "$CODE/bootstrap/cache/config.php" "$CODE/bootstrap/cache/routes-v7.php" "$CODE/bootstrap/cache/events.php"

created_env=false
if [ ! -f "$CONFIG/.env" ] && [ -f "$CODE/.env.prod" ]; then
    cp "$CODE/.env.prod" "$CONFIG/.env"
    created_env=true
fi

if [ ! -f "$CONFIG/.env" ]; then
    echo "WARNING: $CONFIG/.env is missing: write it and run suricatavel-agent-setup again."
    exit 0
fi

chown "$SERVICE_USER:$GROUP" "$CONFIG/.env"
chmod 0600 "$CONFIG/.env"

if [ "$created_env" = true ]; then
    as_agent key:generate --force || echo 'Warning: php artisan key:generate failed'
fi
as_agent migrate --force || echo 'Warning: php artisan migrate --force failed'
