#!/bin/bash
# ===============================================================
#
# HELPER: move existing hooks to new hook structure
#
# ---------------------------------------------------------------
# 2022-11-04  axel.hahm@iml.unibe.ch
# ===============================================================

cd "$( dirname $0 )/../hooks"


# ---------------------------------------------------------------
# CONFIG
# ---------------------------------------------------------------

typeset -i iFound=0
declare -a aOldHooks=(
    10-before-backup
    12-before-db-service
    14-before-db-dump
    16-after-db-dump
    18-after-db-service
    20-before-transfer
    22-before-folder-transfer
    24-after-folder-transfer
    26-after-prune
    28-after-verify
    30-post-backup
)

declare -a aNewHooks=(
    100-before-backup
    200-before-db-service
    210-before-db-dump
    220-after-db-dump
    230-after-db-service
    300-before-transfer
    310-before-folder-transfer
    320-after-folder-transfer
    330-after-prune
    340-after-verify
    400-post-backup
)

# ---------------------------------------------------------------
# MAIN
# ---------------------------------------------------------------

echo
echo ===== HELPER: move existing hooks to new hook structure =====
echo

for i in ${!aOldHooks[@]}
do
    hookfrom=${aOldHooks[$i]}
    hookto=${aNewHooks[$i]}

    if [ -d "$hookto" ]; then
        if [ -d "$hookfrom" ]; then
            echo "  SCAN for $hookfrom ... "
            for myfile in $( find $hookfrom -type f | grep -v ".gitignore" )
            do
                tofile=$( echo $myfile | sed "s#$hookfrom#$hookto#" )
                echo -n "  MOVE $myfile -> $tofile ... "
                mv "$myfile" "$tofile" && echo "OK" || echo "FAILED"
                iFound+=1
            done
            find $hookfrom -type f | grep -v ".gitignore" && echo "  WARNING: some files are still in [$hookfrom] " || (
                echo -n "  no more files ... REMOVE [$hookfrom] ... "
                rm -rf "$hookfrom" && echo "OK" || echo "FAILED"
            )
            echo
        else
            echo "SKIP $hookto - nothing to do."
        fi
    else
        echo "ERROR: hook dir $hookto does not exist"
    fi
done

echo "----------------------------------------------------------------------"
echo "moved files: $iFound"

# ---------------------------------------------------------------
