#!/bin/sh -eu
# ###########################################################################
#             Thomas Dreibholz's R Simulation Scripts Collection
#                  Copyright (C) 2005-2025 Thomas Dreibholz
#
#               Author: Thomas Dreibholz, thomas.dreibholz@gmail.com
# ###########################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com

# ====== Check parameters ===================================================
if [ $# -lt 1 ] ; then
   echo >&2 "Usage: $0 [Simulation]"
   exit 1
fi
SIMULATION="$1"
if [ ! -e "$SIMULATION" ] ; then
   echo "ERROR: Directory $SIMULATION does not exist!"
   exit
fi
if [ ! -e "$SIMULATION/dependencies.list" ] ; then
   echo "ERROR: $SIMULATION/dependencies.list does not exist!"
   exit
fi


echo "Finding obsolete runs ..."

# Generate an SED script to remove in-use file prefixes from file prefix list ...
xargs -r -I{} echo "s|^{}-.*$||g" < "$SIMULATION/dependencies.list" >"$SIMULATION/purge.sed"
# cat "$SIMULATION/purge.sed"

# Get list of obsolete file prefixes
rm -f "$SIMULATION/purge.list"
find "$SIMULATION/Simulations/" -type f -and -name "run[0-9]*-*" | \
   sed -f "$SIMULATION/purge.sed" -e '/^$/ d' \
      >"$SIMULATION/purge.list"
# cat "$SIMULATION/purge.list"


echo "Removing obsolete runs ..."

xargs -r -I{} rm -f "{}" <"$SIMULATION/purge.list"
find "$SIMULATION/Simulations/" -mindepth 1 -maxdepth 1 -and -type d -print0 | xargs -0 -r -I{} rmdir --ignore-fail-on-non-empty "{}"
find "$SIMULATION/Simulations/" -name "Shortcut-*" -print0 | xargs -0 -r -I{} rm -f "{}"
rm -f "$SIMULATION/purge.list" "$SIMULATION/purge.sed" "$SIMULATION/make.log"


echo "Done!"
