#!/bin/sh
#  This script migrates a numbered gdi-link-tx backfill directory cleaner
#  to a named instance directory cleaner.

# Only run once
[ -n "${POST_UPGRADE_CACHE}" ] && touch "${POST_UPGRADE_CACHE}/`basename $0`"

echo " * Migrating gdi-link-tx directory-cleaner files"
# Are there any numbered directory cleaners already setup for gdi-link-tx instances ?

GDILINKTXDIR=/etc/gdi-link-tx
DCDIR=/etc/directory-cleaner

for file in ${GDILINKTXDIR}/default.local ${GDILINKTXDIR}/[0-9].local ${GDILINKTXDIR}/[0-9][0-9].local
do
    if [ -r $file ]
    then
        exist=0
        instance=`basename $file .local`

        # Check if backfill is enabled in this instance
        x=`gcs_rwvar 'gcs_is_true_varcf2' backfill_enabled "${file}" ''`
        disabled=$?
        bfdirectory=`gcs_rwvar gcs_get_varcf "backfill_directory" "$file"`

	# Even if backfill is disabled if there is a cleaner setup we should migrate it.
	for dcfile in ${DCDIR}/[0-9].local ${DCDIR}/[0-9][0-9].local
	do
            if [ -r $dcfile ]
            then
	        dcdirectory=`gcs_rwvar gcs_get_varcf "directory" "$dcfile"`
		if [ "$bfdirectory" = "$dcdirectory" ]
		then
		    echo "   Moving $dcfile to ${DCDIR}/gdi-link-tx.${instance}.local"
		    mv -f $dcfile ${DCDIR}/gdi-link-tx.${instance}.local
                    exist=1
		fi
            fi
	done

	# Only create new cleaner if backfill is enabled
	if [ $disabled -eq 0 ]
	then
            # Backfill is enabled but there is no numbered directory cleaner setup
            # Is there a named one ?
            if [ -r ${DCDIR}/gdi-link-tx.${instance}.local ]
            then
                exist=1
            fi

            # If there isn't one we need to create one
            if [ $exist -ne 1 ]
            then
                cat > $DCDIR/gdi-link-tx.${instance}.local <<EOF
# File created by /usr/lib/upgrade/4035-migrate-gdi-link-tx-backfill-cleaner.sh $(isodate -e)
directory = $bfdirectory
filesort = lexical
maximum_size = 50
maximum_files = 24
EOF
            echo "   Creating $DCDIR/gdi-link-tx.${instance}.local"
            fi
        fi
    fi
done


exit 0
