#!/usr/bin/env bash
# entrypoint.sh — prepare the bind-mounted afaq app, write the bundled SFTP
# server's credentials into .env, then start Apache. Runs as root.
set -e

cd /var/www/html

a2enmod rewrite headers ssl >/dev/null 2>&1 || true

# ---------------------------------------------------------------------------
# Self-signed TLS cert for the :443 vhost (only if none was provided).
# ---------------------------------------------------------------------------
if [ ! -f /etc/apache2/ssl/cert.pem ] || [ ! -f /etc/apache2/ssl/key.pem ]; then
    echo "[entrypoint] generating self-signed TLS certificate"
    mkdir -p /etc/apache2/ssl
    openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
        -keyout /etc/apache2/ssl/key.pem \
        -out    /etc/apache2/ssl/cert.pem \
        -subj   "/C=OM/ST=Local/L=Local/O=Afaq/CN=localhost" >/dev/null 2>&1 || \
        echo "[entrypoint] WARN: cert generation failed — HTTPS vhost may not start"
fi

# ---------------------------------------------------------------------------
# Point afaq's FTP file driver at the bundled sftp container on every `up`, so
# uploads go to host "sftp" (port 22) and are served back over http://sftp/<path>.
# The values come from the compose environment (single source of truth, shared
# with the sftp service).
#
# These keys already exist in .env (SFTP_HOST/SFTP_USER/SFTP_PASSWORD), so we edit
# their values in place. FILE_SYSTEM_DRIVER is appended only if absent.
# ---------------------------------------------------------------------------
ENV_FILE=".env"

# upsert KEY VALUE: replace the value of an existing "KEY=" line, else append it.
upsert_env() {
    key="$1"; val="$2"
    if grep -qE "^[[:space:]]*${key}=" "$ENV_FILE"; then
        sed -i -E "s|^[[:space:]]*${key}=.*|${key}=\"${val}\"|" "$ENV_FILE"
    else
        echo "${key}=\"${val}\"" >> "$ENV_FILE"
    fi
}

if [ -f "$ENV_FILE" ]; then
    upsert_env "FILE_SYSTEM_DRIVER" "${FILE_SYSTEM_DRIVER:-FTP}"
    upsert_env "SFTP_HOST"          "${SFTP_HOST:-sftp}"
    upsert_env "SFTP_USER"          "${SFTP_USER:-afaq_ftp_user}"
    upsert_env "SFTP_PASSWORD"      "${SFTP_PASS:-afaq_ftp_pwd}"
    echo "[entrypoint] updated .env SFTP credentials (host=${SFTP_HOST:-sftp}, user=${SFTP_USER:-afaq_ftp_user})"
else
    echo "[entrypoint] WARN: .env not found — skipped SFTP credential injection"
fi

# afaq caches .env into bootstrap/cache/env.php (mtime-guarded). We just touched
# .env so the cache is stale; delete it to force a clean reparse.
rm -f bootstrap/cache/env.php

# ---------------------------------------------------------------------------
# Runtime dirs + permissions. On Windows bind mounts chown is often a no-op
# (the mount is world-writable) and that's fine; on Linux/macOS it grants
# www-data write access.
# ---------------------------------------------------------------------------
mkdir -p \
    storage/logs \
    storage/cache \
    storage/sessions \
    storage/views \
    storage/meta \
    bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true
chmod -R ug+rwX           storage bootstrap/cache 2>/dev/null || true

echo "[entrypoint] starting Apache (DocumentRoot=public_html)"
exec apache2-foreground
