#!/bin/bash
##############################################################################
# Copyright (c) Members of the EGEE Collaboration. 2004.
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

function check_schema () {

DPM_DB_HOST=$1
DPM_DB_USER=$2
DPM_DB_PASSWORD=$3
DPM_DB=$4
DPNS_DB=$5
DPM_VERSION=$6
DPNS_VERSION=$7

# Gets the cns and dpm db's schema version
echo "Checking for database schema version... "

aux=`mysql --skip-column-names -s -h ${DPM_DB_HOST} -u ${DPM_DB_USER} --pass="${DPM_DB_PASSWORD}" -e "use ${DPM_DB}; select * from schema_version_dpm;" 2> /dev/null`
if [ $? -ne 0 ]; then
  echo "No DPM database schema version information found. Exiting."
  return 1
fi
dpmvdots=`echo $aux | awk '{print $1"."$2"."$3}'`
dpmv=`echo $aux | awk '{print $1$2$3}'`

aux=`mysql --skip-column-names -s -h ${DPM_DB_HOST} -u ${DPM_DB_USER} --pass="${DPM_DB_PASSWORD}" -e "use ${DPNS_DB}; select * from schema_version;" 2> /dev/null`
if [ $? -ne 0 ]; then
  echo "No DPNS database schema version information found. Exiting."
  return 1
fi
cnsvdots=`echo $aux | awk '{print $1"."$2"."$3}'`
cnsv=`echo $aux | awk '{print $1$2$3}'`

echo "Database versions used: DPM $dpmvdots - DPNS $cnsvdots"

upgrade=0
if [ $dpmv -lt $DPM_VERSION ]; then
  echo "DPM DB needs to be upgraded... "
  upgrade=1
fi

if [ $cnsv -lt $DPNS_VERSION ]; then
  echo "DPNS DB needs to be upgraded... "
  upgrade=1
fi

return $upgrade
}

#default values
dpmv='350'
dpnsv='320'
dpm_db='dpm_db'
dpns_db='cns_db'
 
if [ "$#" -gt 3 ]; then
        dpm_db=$4
        dpns_db=$5
fi

if [ "$#" -gt 5 ]; then
        dpmv=$6
        dpnsv=$7
fi

check_schema $1 $2 $3 $dpm_db $dpns_db $dpmv $dpnsv
