#!/bin/sh
export LC_ALL=C

# respect --keep-prefix[=..] 1st arg, else delete prefix only if zero arguments.
keep_prefix=yes
[ $# = 0 ] && keep_prefix=no
[ "${1-}" = "--keep-prefix=no" ] && keep_prefix=no && shift
[ "${1-}" = "--keep-prefix=yes" ] && keep_prefix=yes && shift
[ "${1-}" = "--keep-prefix" ] && keep_prefix=yes && shift

cd "$(dirname "$0")"
config_process_projects_cli=yes
. scripts/core-config || exit 1
. pkg/pkg-utils.sh

hook_or_die "$config_clean_pre" clean-pre

# on errors we warn and continue, but finally exit with error code 1
fail=
for p in $config_projects; do
    highlight_msg "($config_projects) cleaning $p"
    if pkg_has $p; then
        (pkg_load $p && pkg_clean) || { warn_msg "failed to clean '$p'"; fail=yes; }
    elif [ -e scripts/${p}-clean ]; then
        scripts/${p}-clean || { warn_msg "failed to clean '$p'"; fail=yes; }
    else
        echo "No clean (empty)"
    fi
done

if [ no = "$keep_prefix" ]; then
    highlight_msg "($config_projects) deleting local prefix dir"
    # the prefix dir exists - ensured at scripts/core-config earlier
    if ! [ -e "$config_local_prefix"/core-prefix ]; then
        warn_msg "$config_local_prefix is not a dir we created, not deleting"
        info_msg "to allow deletion, run 'touch $config_local_prefix/core-prefix'"
        fail=yes
    else
        rm -rf "$config_local_prefix" ||
            { warn_msg "failed to delete '$config_local_prefix'"; fail=yes; }
    fi
fi

hook_or_die "$config_clean_post" clean-post

[ "$fail" ] && warn_msg "($config_projects) some cleanups failed" && exit 1
success_msg "cleaned: $config_projects"
