#!/usr/bin/env bash
# Sets ownership/permissions for the barox Virtual Switch Simulator so that
# Apache (www-data) and the systemd worker services (also www-data) can
# read the application and write logs, without making anything
# world-writable. Run with sudo.
set -euo pipefail

APP_DIR="/var/www/html/barox-swtsim"
LOG_DIR="/var/log/barox-switch-simulator"
WEB_USER="www-data"
WEB_GROUP="www-data"

if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root (sudo scripts/permissions.sh)." >&2
    exit 1
fi

if [ ! -d "$APP_DIR" ]; then
    echo "Application directory $APP_DIR not found." >&2
    exit 1
fi

mkdir -p "$LOG_DIR"
chown -R "$WEB_USER:$WEB_GROUP" "$LOG_DIR"
chmod 750 "$LOG_DIR"

chown -R "$WEB_USER:$WEB_GROUP" "$APP_DIR"
find "$APP_DIR" -type d -exec chmod 750 {} \;
find "$APP_DIR" -type f -exec chmod 640 {} \;
chmod 750 "$APP_DIR"/scripts/*.sh "$APP_DIR"/workers/*.php

if [ -f "$APP_DIR/config/local.php" ]; then
    chmod 640 "$APP_DIR/config/local.php"
fi

echo "Permissions set for $APP_DIR and $LOG_DIR (owner $WEB_USER:$WEB_GROUP)."
