#!/bin/bash
# Background recording-permission repair, off the blocking pre-start path (the
# recursive sweep can exceed the systemd start timeout on a large tree).
set -u

PKG="unifi-protect"
USER="unifi-protect"
GROUP="unifi-streaming"
STATE_DIR="/run/${PKG}-permission-repair"
TREES_FILE="${STATE_DIR}/trees"
STAMP="${STATE_DIR}/stamp"
LOCK="${STATE_DIR}/lock"
INTERNAL_DIR="${UFP_INTERNAL_DIR:-/data/${PKG}}"
EXTERNAL_DIR="${UFP_EXTERNAL_DIR:-/srv/${PKG}}"
# Skip re-walking on rapid restarts (crash loop); a changed signature still runs.
MIN_INTERVAL_SECONDS=$((20 * 3600))
# After a failed run, retry at most this often instead of re-walking on every start.
RETRY_INTERVAL_SECONDS=3600

log() { echo "permission-repair: $*" 1>&2; }

# Root sweep touches only known recording roots. Keep in sync with pre-start's
# queue_permission_repair — a queued path not allowed here is refused, not repaired.
is_allowed_tree() {
  case "$1" in
    "${INTERNAL_DIR}/video"|"${EXTERNAL_DIR}/video"|"${INTERNAL_DIR}/exports"|"${EXTERNAL_DIR}/exports")
      return 0 ;;
    /volume/*/unifi-protect/video)
      local rest="${1#/volume/}" uuid
      uuid="${rest%%/*}"
      case "$uuid" in
        ''|*[!0-9A-Fa-f-]*) return 1 ;;
      esac
      # case '*' spans '/'; exact-match the canonical form to reject extra segments / '..'.
      [ "$1" = "/volume/${uuid}/unifi-protect/video" ] && return 0
      return 1 ;;
  esac
  return 1
}

# Trees that get owner+group normalized; the large video trees are group-only.
repairs_owner() {
  case "$1" in
    "${INTERNAL_DIR}/video"|"${INTERNAL_DIR}/exports"|"${EXTERNAL_DIR}/exports") return 0 ;;
  esac
  return 1
}

# Root-owned /run parent blocks symlink planting; tmpfs stamp resets on reboot (fine — reboot is a start).
install -d -m 0700 -o root -g root "$STATE_DIR" 2>/dev/null || true

# No 2>/dev/null here: on a command-less exec it would silence the whole script's stderr.
exec 9>"$LOCK" || { log "cannot open lock $LOCK; skipping"; exit 0; }
flock -n 9 || { log "another repair is already running; skipping"; exit 0; }

[ -s "$TREES_FILE" ] || { log "no work list; nothing to do"; exit 0; }
mapfile -t TREES < <(sort -u "$TREES_FILE")

# Re-run when the tree set or a tree's backing device changes; postinst clears the stamp on upgrade.
# Collapse findmnt to one line per tree — it can print multiple SOURCE rows, and the signature is one line.
roots=""
for t in "${TREES[@]}"; do
  [ -d "$t" ] || continue
  dev="$(findmnt -no SOURCE --target "$t" 2>/dev/null | sort -u | paste -sd'+' -)"
  roots="${roots},${dev:-?}"
done
signature="trees=$(printf '%s,' "${TREES[@]}")|roots=${roots}"

now="$(date +%s)"
if [ -f "$STAMP" ]; then
  old_sig="$(sed -n 's/^SIG=//p' "$STAMP" 2>/dev/null | head -1)"
  old_ts="$(sed -n 's/^TS=//p' "$STAMP" 2>/dev/null | head -1)"
  old_result="$(sed -n 's/^RESULT=//p' "$STAMP" 2>/dev/null | head -1)"
  age=$(( now - ${old_ts:-0} ))
  if [ "$old_sig" != "$signature" ]; then
    reason="signature changed"
  elif [ "$old_result" != "ok" ]; then
    # Back off failed retries so a persistent error on a crash loop can't re-walk every start.
    if [ "$age" -ge 0 ] && [ "$age" -lt "$RETRY_INTERVAL_SECONDS" ]; then
      log "skip: previous run had errors ${age}s ago; retrying after ${RETRY_INTERVAL_SECONDS}s"
      exit 0
    fi
    reason="retry after previous errors (last run ${age}s ago)"
  else
    if [ "$age" -ge 0 ] && [ "$age" -lt "$MIN_INTERVAL_SECONDS" ]; then
      log "skip: unchanged since last repair ${age}s ago"
      exit 0
    fi
    reason="periodic (last run ${age}s ago)"
  fi
else
  reason="first run"
fi

log "starting (reason: ${reason}); trees: ${TREES[*]}"
start="$now"
failed=0
for t in "${TREES[@]}"; do
  if ! is_allowed_tree "$t"; then
    log "WARNING: refusing unexpected path: $t"; failed=1; continue
  fi
  [ -d "$t" ] || { log "skip missing tree: $t"; continue; }
  t_start="$(date +%s)"
  if repairs_owner "$t"; then
    own_pred=( '(' '!' -user "$USER" -o '!' -group "$GROUP" ')' ); own_spec="$USER:$GROUP"
  else
    own_pred=( '!' -group "$GROUP" ); own_spec=":$GROUP"
  fi
  # Dirs need g+rwx (traverse into), files g+rw. The type filter + chown -h keep every action off symlinks.
  # find exits non-zero on benign ENOENT (a clip rotated mid-walk), so judge failure by non-ENOENT stderr.
  # awk streams that stderr to a count + 3-line sample so a flood of errors can't buffer unbounded (OOM).
  summary="$(LC_ALL=C find "$t" -xdev '(' -type d -o -type f ')' '(' \
        '(' -type d '!' -perm -g=rwx -exec chmod g+rwx -- {} + ')' , \
        '(' -type f '!' -perm -g=rw  -exec chmod g+rw  -- {} + ')' , \
        '(' "${own_pred[@]}" -exec chown -h "$own_spec" -- {} + ')' \
      ')' 2>&1 >/dev/null \
      | grep -v 'No such file or directory' \
      | awk '{ n++; if (n<=3) s = s (n>1 ? "; " : "") $0 } END { if (n) printf "%d\t%s", n, s }')"
  if [ -n "$summary" ]; then
    n_errs=${summary%%$'\t'*}; sample=${summary#*$'\t'}
    log "WARNING: repair of $t reported ${n_errs} error(s) after $(( $(date +%s) - t_start ))s: ${sample}"; failed=1
  else
    log "repaired $t in $(( $(date +%s) - t_start ))s"
  fi
done

result="ok"; [ "$failed" -eq 0 ] || result="errors"
# Stamp TS at completion so the interval measures from when the repair finished.
{ echo "SIG=$signature"; echo "TS=$(date +%s)"; echo "COMPLETED=$(date -u +%FT%TZ)"; echo "DURATION_S=$(( $(date +%s) - start ))"; echo "RESULT=$result"; } > "$STAMP" 2>/dev/null || true
log "complete in $(( $(date +%s) - start ))s (result: ${result})"
# Non-zero exit marks the oneshot 'failed' (surfaces in systemctl --failed / support bundles).
[ "$failed" -eq 0 ] && exit 0
exit 1
