#!/usr/bin/env bash
set -euo pipefail

# ======================================================================
# obm-project-permissions.sh — Set correct chmod/chown permissions for an
#                              OpenBAM frontend project
#
# Usage: obm-project-permissions.sh <project_name> [owner_user]
#
#   <project_name>  required — project directory name under /var/www/projects
#   [owner_user]    optional — the non-www-data owner. If omitted the owner is
#                  auto-resolved: the current user on developer workstations
#                  (e.g. hje on arkon), "root" when run as root, otherwise
#                  "debian" (the default on the staging/production servers).
#
#   Examples:
#     obm-project-permissions.sh dylanwatts.de            # server default
#     obm-project-permissions.sh dylanwatts.de hje        # on arkon
#     obm-project-permissions.sh dylanwatts.de root       # on dwsrv
#
#   Applies the permission model documented in
#   assets/docs/manuals/OBM_Project_Permissions_Manual.md:
#
#     STAGING   (hostname equals project.ini [servers] staging, e.g. "vega")
#       www-data owns the CMS/runtime write targets:
#         articles/ cache/ dbase/ modules/ config/
#       <owner> owns everything else (code stays read-only for www-data)
#
#     PRODUCTION (all other hosts, e.g. arkon, dwsrv, terra)
#       <owner> owns everything; only cache/ and dbase/ are owned by www-data
#
#   File modes: directories 755, files 644. Execute bits on *.sh files are
#   preserved. The .git directory is excluded from chmod and left to <owner>
#   (see the manual, section "The .git Ownership Conflict").
# ======================================================================

PROJECTS_ROOT="/var/www/projects"
WEB_USER="www-data"

usage() {
    echo "Usage: $0 <project_name> [owner_user]"
    echo ""
    echo "  Sets chmod/chown permissions for an OpenBAM frontend project."
    echo ""
    echo "  Arguments:"
    echo "    project_name  Project directory under $PROJECTS_ROOT (e.g. dylanwatts.de)"
    echo "    owner_user    Optional. Owner for all non-www-data files. Default:"
    echo "                  current user on developer workstations (hje on arkon),"
    echo "                  root when run as root, otherwise debian."
    echo ""
    echo "  Examples:"
    echo "    $0 dylanwatts.de"
    echo "    $0 dylanwatts.de hje"
    echo "    $0 dylanwatts.de root"
    exit 1
}

PROJECT="${1:-}"
if [[ -z "$PROJECT" ]]; then
    echo "ERROR: Project name is required."
    usage
fi

if [[ ! "$PROJECT" =~ ^[A-Za-z0-9._-]+$ ]]; then
    echo "ERROR: Invalid project name: $PROJECT"
    exit 1
fi

PROJECT_DIR="$PROJECTS_ROOT/$PROJECT"
if [[ ! -d "$PROJECT_DIR" ]]; then
    echo "ERROR: Project directory not found: $PROJECT_DIR"
    exit 1
fi

# --- Resolve owner ----------------------------------------------------
OWNER="${2:-}"
if [[ -z "$OWNER" ]]; then
    CURRENT_USER="$(id -un)"
    if [[ "$CURRENT_USER" == "root" ]]; then
        OWNER="root"
    elif [[ "$CURRENT_USER" == "debian" || "$CURRENT_USER" == "$WEB_USER" ]]; then
        OWNER="debian"
    else
        OWNER="$CURRENT_USER"
    fi
fi

if ! id -u "$OWNER" >/dev/null 2>&1; then
    echo "ERROR: Unknown user: $OWNER"
    exit 1
fi

# --- Use sudo only when not already root ------------------------------
if [[ "$(id -u)" -eq 0 ]]; then SUDO=""; else SUDO="sudo"; fi

# --- Detect permission model (mirrors CmsGitHookTrait staging check) --
MODEL="production"
STAGING_HOST=""
CONFIG="$PROJECT_DIR/config/sets/project.ini"
if [[ -f "$CONFIG" ]]; then
    STAGING_HOST=$(awk '
        /^\[servers\]/  { inservers = 1; next }
        /^\[/           { inservers = 0 }
        inservers && /^[[:space:]]*staging[[:space:]]*=/ {
            sub(/^[^=]*=[[:space:]]*/, "");
            gsub(/[",;]/, "");
            gsub(/^[[:space:]]+|[[:space:]]+$/, "");
            print; exit
        }
    ' "$CONFIG")
fi

if [[ -n "$STAGING_HOST" && "$STAGING_HOST" == "$(hostname)" ]]; then
    MODEL="staging"
fi

echo "============================================"
echo "OpenBAM Project Permissions"
echo "Started:  $(date '+%Y-%m-%d %H:%M:%S')"
echo "Project:  $PROJECT_DIR"
echo "Owner:    $OWNER  (web user: $WEB_USER)"
echo "Model:    $MODEL  (staging host: ${STAGING_HOST:-none})"
echo "============================================"

# --- 1) Base ownership: everything belongs to the owner ---------------
echo "[1/4] Chowning project to $OWNER:$OWNER ..."
$SUDO chown -R "$OWNER:$OWNER" "$PROJECT_DIR"

# --- 2) Write-target ownership for the web user -----------------------
if [[ "$MODEL" == "staging" ]]; then
    echo "[2/4] Staging: chowning CMS/runtime write targets to $WEB_USER:$WEB_USER ..."
    TARGETS=(articles cache dbase modules config)
else
    echo "[2/4] Production: chowning cache/ and dbase/ to $WEB_USER:$WEB_USER ..."
    TARGETS=(cache dbase)
fi

for dir in "${TARGETS[@]}"; do
    if [[ -d "$PROJECT_DIR/$dir" ]]; then
        $SUDO chown -R "$WEB_USER:$WEB_USER" "$PROJECT_DIR/$dir"
    fi
done

# --- 3) File modes: dirs 755, files 644, *.sh executable --------------
echo "[3/4] Setting file modes (dirs 755, files 644, *.sh executable) ..."
$SUDO find "$PROJECT_DIR" \( -name .git -type d -prune \) -o -type d -exec chmod u=rwX,g=rX,o=rX {} +
$SUDO find "$PROJECT_DIR" \( -name .git -type d -prune \) -o -type f -exec chmod u=rwX,g=rX,o=rX {} +
$SUDO find "$PROJECT_DIR" \( -name .git -type d -prune \) -o -type f -name '*.sh' -exec chmod u+x,g+x,o+x {} +

# --- 4) Security: strip world-writable bits (never in .git) -----------
echo "[4/4] Removing world-writable bits ..."
$SUDO find "$PROJECT_DIR" \( -name .git -type d -prune \) -o -type f -perm -0002 -exec chmod o-w {} +

echo ""
echo "============================================"
echo "PERMISSIONS SET"
echo "Finished: $(date '+%Y-%m-%d %H:%M:%S')"
echo "============================================"

if [[ "$MODEL" == "staging" ]]; then
    echo ""
    echo "Note (staging): the CMS auto-commit hook runs git as $WEB_USER."
    echo "  For CMS dashboard commits:  $SUDO chown -R $WEB_USER:$WEB_USER \"$PROJECT_DIR/.git\""
    echo "  For developer git ops:      $SUDO chown -R $OWNER:$OWNER \"$PROJECT_DIR/.git/objects\""
fi
