#!/usr/bin/env bash

set -euo pipefail

APP_ROOT="${APP_ROOT:-/var/www/html}"
BOOTSTRAP_CACHE_DIR="${APP_ROOT}/bootstrap/cache"
STORAGE_ROOT="${APP_ROOT}/storage"
LOG_DIR="${STORAGE_ROOT}/logs"

RUNTIME_DIRS=(
    "${BOOTSTRAP_CACHE_DIR}"
    "${STORAGE_ROOT}/framework/cache/data"
    "${STORAGE_ROOT}/framework/sessions"
    "${STORAGE_ROOT}/framework/views"
    "${LOG_DIR}"
)

ensure_runtime_dirs() {
    local dir

    for dir in "${RUNTIME_DIRS[@]}"; do
        mkdir -p "${dir}"
    done

    chown -R www-data:www-data "${STORAGE_ROOT}" "${BOOTSTRAP_CACHE_DIR}" 2>/dev/null || true
    chmod -R 775 "${STORAGE_ROOT}" "${BOOTSTRAP_CACHE_DIR}" 2>/dev/null || true
}

touch_runtime_logs() {
    touch "${LOG_DIR}/laravel.log" "${LOG_DIR}/queue.log"
    chown www-data:www-data "${LOG_DIR}/laravel.log" "${LOG_DIR}/queue.log" 2>/dev/null || true
    chmod 664 "${LOG_DIR}/laravel.log" "${LOG_DIR}/queue.log" 2>/dev/null || true
}

run_as_www_data() {
    local command="$1"

    if [[ "$(id -u)" == "0" ]]; then
        su -s /bin/bash www-data -c "cd \"${APP_ROOT}\" && ${command}"
        return
    fi

    bash -lc "cd \"${APP_ROOT}\" && ${command}"
}

exec_as_www_data() {
    local command="$1"

    if [[ "$(id -u)" == "0" ]]; then
        exec su -s /bin/bash www-data -c "cd \"${APP_ROOT}\" && ${command}"
    fi

    exec bash -lc "cd \"${APP_ROOT}\" && ${command}"
}
