#!/bin/bash
set -euo pipefail

usage() {
  cat <<EOF
Usage: $(basename "$0") <caseDir>

Cleans up subdirectories inside the given directory:
  - cubes
  - restart
  - stats
  - database

Options:
  --help    Show this help message and exit
  -c    Do NOT delete "cubes/"
  -r    Do NOT delete "restart/"
  -s    Do NOT delete "stats/"
  -d    Do NOT delete "database/"

Example:
  $(basename "$0") <caseDir>      # Clears all subdirectories generated by AMPHIBIOUS
  $(basename "$0") <caseDir> -rc  # Clears only stats/ and database/ subdirectories
EOF
}

if [[ $# -eq 0 ]] || [[ "$1" == "--help" ]]; then
  usage
  exit 0
fi
# Get the first argument passed to the script
dir="$1"
shift || true 

# Check if well formatted (ends with "/")
case "$dir" in
  */) ;; 
  *) dir="${dir}/" ;;
esac

delCubes=true
delRestart=true
delStats=true
delDatabase=true

# Parse skip flags
if [[ $# -gt 0 ]]; then
  if [[ "$1" =~ ^- ]]; then
    flags="${1#-}"
    [[ "$flags" == *c* ]] && delCubes=false
    [[ "$flags" == *r* ]] && delRestart=false
    [[ "$flags" == *s* ]] && delStats=false
    [[ "$flags" == *d* ]] && delDatabase=false
  fi
fi

# Perform deletions
$delCubes     && rm -rf "${dir}cubes"
$delRestart   && rm -rf "${dir}restart"
$delStats     && rm -rf "${dir}stats"
$delDatabase  && rm -rf "${dir}database"
