#!/bin/sh

# this script creates the files needed by dbc for database updates.

# this script needs to be augmented whenever there is a new database update,
# in particular "lastdbversion" and the case statements need to be reviewed.

# first and last target database version covered by this script
dbtarget=13
lastdbversion=15

variants="mysql pgsql sqlite3"

dbc="usr/share/dbconfig-common/data"
extractor="debian/scripts/extract-dbupgrade.awk"


while [ $dbtarget -le $lastdbversion ]; do
    for db in $variants; do
	if [ $db = pgsql ] ; then
	    longdb=postgresql
	else
	    longdb=$db
	fi

	case $dbtarget in
	    13)	baculaversion="5.2.0"
		;;
	    14)	baculaversion="5.2.0"
		;;
	    15)	baculaversion="7.2.0"
		;;
	    *)	echo "$0: Unknown database target version"
		exit 1
		;;
	esac

	sourcefile="src/cats/update_"$longdb"_tables"
	targetfile="debian/bacula-director-"$db"/"$dbc"/bacula-director-"$db"/upgrade/"$db"/"$baculaversion;

	awk -v version=$dbtarget -f $extractor $sourcefile >> $targetfile

	# special handling for pgsql, there's extra code at the end of
	# the upgrade script that we use for updates to version 15
	# - sh compatible improvements welcome :-)
	if [ $db = pgsql ]; then
	    if [ $dbtarget -eq 15 ]; then
		# the double awk invocation tries to make extra sure we get the correct instructions
		awk '/For all versions, we need to create the Index on Media/ , /^END-OF-DATA$/' $sourcefile | awk '/set client_min_messages/, /CREATE INDEX media_storageid_idx ON Media/' >> $targetfile
	    fi
	fi

    done

    dbtarget=$((dbtarget + 1))
done
