#!/bin/bash

upgradeDataBase() {
        COUNTER=1
        echo "Upgrading $1 database"

        psql -U postgres -h 127.0.0.1 -d $1 -f /etc/coraltele/database/dropfunction.sql
        psql -U postgres -h 127.0.0.1 -d $1 -c "select * from dropdatabaseobjects()"


        while [  $COUNTER -lt 11 ]; do
                echo "$1 : Iteration no $COUNTER"
                pg_dump -h 127.0.0.1 -U postgres -s -O -n $2 $1 > /tmp/$2.schema
                #pg_dump -s -O -U postgres -d $1 -h 127.0.0.1 > /tmp/$1.schema
                upgradeFile="/tmp/$2.upgrade.sql"
                rm $upgradeFile

                if [ $psqlVersion == "12.5" ]; then
                        java -jar /etc/coraltele/apgdiff-2.4.jar /tmp/$2.schema /etc/coraltele/database/$2.schema > $upgradeFile
                else
                        java -jar /etc/coraltele/apgdiff-2.4.jar /tmp/$2.schema /etc/coraltele/database/$2.schema.v8 > $upgradeFile
                fi

                if [ -s "$upgradeFile" ]; then
                psql -U postgres -h 127.0.0.1 -d $1 -f $upgradeFile > /tmp/upgradeoutput
                else
                echo "$1 : Upgraded"
                break
                fi
            COUNTER=$(expr $COUNTER + 1)
        done

        if [ $COUNTER = 11 ]; then
                echo "*********************************************************************************************"
                echo "!!!!! Unable to upgrade $1 , please send $upgradeFile !!!!!"
                echo "*********************************************************************************************"
                sleep 5
        fi
}


dbConnect=$(psql -h 127.0.0.1 -U postgres -c "select 1" | grep ?column? | wc -l)
psqlVersion=$(dpkg-query -l | grep postgresql-client-12 | awk '{print $3}' | sed 's/-.*//')

if [ $dbConnect -eq 0 ]; then
    echo `date` "Database not available"
else
    echo `date` "Database available upgrading the schema"
        upgradeDataBase opennms coralnms 0 ""
fi
