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

# shellcheck source=common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/common.sh"

ensure_env_file
ensure_paths_defined

FORCE=false
while [[ $# -gt 0 ]]; do
  case "$1" in
    -y|--yes)
      FORCE=true
      ;;
    -h|--help)
      cat <<USAGE
Usage: ${0##*/} [--yes]

Safely remove debug private directories after adjusting ownership.
USAGE
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      exit 1
      ;;
  esac
  shift
done

if [[ $FORCE == false ]]; then
  read -r -p "This will delete debug private directories. Continue? [y/N] " reply
  case "$reply" in
    y|Y|yes|YES)
      ;;
    *)
      echo "Aborted"
      exit 0
      ;;
  esac
fi

paths=(
  "$SYS_DEBUG_PRIVATE_CORE"
  "$SYS_DEBUG_PRIVATE_NODEA"
  "$SYS_DEBUG_PRIVATE_NODEB"
  "$SYS_DEBUG_TMP_DIR"
)

require_docker

image="ubuntu:22.04"

for dir in "${paths[@]}"; do
  [[ -d "$dir" ]] || continue
  log "Fixing ownership for $dir"
  if ! docker run --rm -v "$dir:/target" "$image" chown -R "$(id -u):$(id -g)" /target >/dev/null 2>&1; then
    echo "[WARN] Failed to adjust ownership via $image, attempting local chown" >&2
    chown -R "$(id -u):$(id -g)" "$dir" >/dev/null 2>&1 || true
  fi
  log "Removing $dir"
  rm -rf "$dir"
done

log "Clean data completed"
