#!/bin/bash
# CLI wrapper — re-exec as WEB_USER (apache) so storage/, plugin settings, and
# plugin-audits cache stay writable.
#   sudo latch plugin enable <slug>
#   sudo latch fix-perms    # repair root-owned plugin storage after a bad sudo php …
set -euo pipefail

LATCH_ROOT="${LATCH_ROOT:-/usr/share/latch/source}"
WEB_USER="${WEB_USER:-apache}"
CLI="${LATCH_ROOT}/bin/latch"

if [[ ! -f "${CLI}" ]]; then
    echo "Error: Latch not installed (${CLI} missing)" >&2
    exit 1
fi

if [[ "$(id -un)" == "${WEB_USER}" ]]; then
    exec php "${CLI}" "$@"
fi

# chown/delete under /usr/share/latch/... — stay root when invoked via sudo latch
if [[ "$(id -un)" == "root" ]]; then
    case "${1:-}" in
        fix-perms)
            if [[ -n "${WEB_USER}" ]]; then
                export LATCH_WEB_USER="${WEB_USER}"
            fi
            exec php "${CLI}" "$@"
            ;;
        plugin)
            if [[ "${2:-}" == "remove" ]]; then
                exec php "${CLI}" "$@"
            fi
            ;;
    esac
fi

if id "${WEB_USER}" >/dev/null 2>&1; then
    exec sudo -u "${WEB_USER}" php "${CLI}" "$@"
fi

exec php "${CLI}" "$@"