#!/bin/bash
# $1 is the directory tree which should be cleaned.
# It may be existing, if not it is created.
# $2 are one-char-options, starting with '-'
#   -D do not remove directories on cleaning the content of $1, prevent the directory tree structure.
# See https://vishia.org/Linux/html/mkSymbLink-de.html
#
# This software may be used, modified, and redistributed under the
# terms of the GNU Lesser General Public License (LGPL).
#
# Author: Dr. Hartmut Schorrig, Germany
# Note: This file was developed with assistance from ChatGPT.
# @date 2026-11-10: created by ChatGPT and Hartmut
#
## On windows execute the Windows version should be found beside.
if test -d /c/Windows; then "$(dirname $0)/cleanDirTree.exe" "$1"; exit $?; fi  
###echo LINUX

DIR="$1"
OPTS="${2-}"

PRESERVE_DIRS=false
[[ "$OPTS" == *D* ]] && PRESERVE_DIRS=true


if [[ -z "$DIR" ]]; then
  echo "ERROR: missing directory argument"
  exit 8
fi

## short explaination: 
# $DIR points to              -f     -L    -d 
# Normal file                 true   false  false
# Symbolic link to file       true   true   false
# Normal directory            false  false  true
# Symbolic link to directory  false  true   true
# Broken symbolic link        false  true   false

## test whether DIR is a regular file, or it is a link but not to a directory:
if [[ -f "$DIR" || ( -L "$DIR" && ! -d "$DIR" ) ]]; then
  rm -f -- "$DIR" || {    ## then remove it.
    ERR=$?
    echo "ERROR $ERR - cannot remove file instead of dir: $DIR"
    exit $ERR
  }
fi

if [[ ! -d "$DIR" ]]; then
  mkdir -p -- "$DIR" || {
    ERR=$?
    echo "ERROR $ERR - cannot create the necessary dir: $DIR"
    exit $ERR
  }
fi

DIRCONTENT="$(ls -A -- "$DIR")"
if ! test -z "$DIRCONTENT"; then
  ## echo "remove content of $DIR: $DIRCONTENT"
  # Remove all contents, including hidden files.
  # find options:
  #  -H accept dir argument as symbolic link, but does not follow symblinks internally
  #  -L would follow symbolic links, this is not desired.
  #  -mindepth 1 do not use the $DIR itself (depth 0) for exec
  #  -maxdepth 1 do not work recursively, only on this depth 1 (because rm do the recursively)
  #  -exec ... + executes the statement 'rm -rf -- {}'
  #    with {} as container for find files.
  # After them || {...} follows for error handling
  # see https://www.man7.org/linux/man-pages/man1/find.1.html
  # if the find with the rm as one combined statement returns not 0.
  if test PRESERVE_DIRS; then   ## find selects regualr files OR ( Links which are not Directories)
    find -H "$DIR"  \( -type f -o \( -type l ! -xtype d \) \)  -delete || {
      ERR=$?
      echo "ERROR $ERR - cannot remove contents inside $DIR"
      exit $ERR
    }
  else
    find -H "$DIR" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + || {
      ERR=$?
      echo "ERROR $ERR - cannot remove contents inside $DIR"
      exit $ERR
    }
  fi
fi
exit 0
