#!/usr/bin/env bash
set -euo pipefail
ROOT=''
OWNER=''
GROUP=''
APPLY=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --root) ROOT="$2"; shift 2 ;;
    --owner) OWNER="$2"; shift 2 ;;
    --group) GROUP="$2"; shift 2 ;;
    --apply) APPLY=1; shift ;;
    *) echo "unknown argument: $1" >&2; exit 2 ;;
  esac
done
[[ -n "$ROOT" && -n "$OWNER" && -n "$GROUP" ]] || { echo 'required: --root PATH --owner USER --group GROUP [--apply]' >&2; exit 2; }
case "$ROOT" in /|/home|/root|/usr|/var) echo "refusing unsafe root: $ROOT" >&2; exit 2;; esac
[[ ! -L "$ROOT" ]] || { echo 'refusing symlink root' >&2; exit 2; }
DIRS=(repos service catalog incoming releases/pfes releases/tools recovery/git-bundles tmp artifacts/irreplaceable artifacts/canonical artifacts/expensive artifacts/quarantine artifacts/scratch)
printf 'Would create under %s:\n' "$ROOT"
printf '  %s\n' "${DIRS[@]}"
[[ $APPLY -eq 1 ]] || { echo 'dry run only; add --apply to create directories'; exit 0; }
umask 0027
install -d -m 0750 -o "$OWNER" -g "$GROUP" "$ROOT"
for d in "${DIRS[@]}"; do
  install -d -m 0750 -o "$OWNER" -g "$GROUP" "$ROOT/$d"
done
cat > "$ROOT/.pf-storage-root.json" <<EOF
{"format":"project-frankenstein-storage-root","version":1,"created_utc":"$(date -u +%Y-%m-%dT%H:%M:%SZ)","protection_status":"single_disk_interim_not_backed_up"}
EOF
chown "$OWNER:$GROUP" "$ROOT/.pf-storage-root.json"
chmod 0640 "$ROOT/.pf-storage-root.json"
echo 'layout initialized; no partition or filesystem operation was performed'
