#!/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 upgrade_stop_services () {
  echo "Stopping DPM services"
  service dpm-gsiftp stop 
  service srmv2.2 stop 
  service dpm stop 
  service dpnsdaemon stop
  service httpd stop
}


function upgrade_start_services () {
  echo "Starting up the DPM services"
  service dpnsdaemon start
  service dpm start
  service srmv2.2 start
  service dpm-gsiftp start
  service httpd start
}


function check_schema_version () {
  DB_HOST=$1
  DB_PORT=$2
  DB_USER=$3
  DB_PASSWORD=$4
  DB_NAME=$5
  DB_TABLE=$6
  DB_VERSION=$7

  version=`mysql --skip-column-names -s -h "${DB_HOST}" -P "${DB_PORT}" -u "${DB_USER}" --pass="${DB_PASSWORD}" -D "${DB_NAME}" -e "select CONCAT(major, minor, patch) from ${DB_TABLE}" 2> /dev/null`
  if [ $? -ne 0 ]; then
    echo "ERROR: No ${DB_NAME} database schema version information found. Exiting."
    exit 1
  fi

  echo $version

  if [ $version -lt $DB_VERSION ]; then
    return 1
  else
    return 0
  fi
}


function upgrade () {
  DB_HOST=$1
  DB_PORT=$2
  DB_USER=$3
  DB_PASS=$4
  DPM_DB=$5
  DPNS_DB=$6
  dpmv=$7
  cnsv=$8

  dpmversion=$(check_schema_version "${DB_HOST}" "${DB_PORT}" "${DB_USER}" "${DB_PASS}" "${DPM_DB}" "schema_version_dpm" "${dpmv}")
  dpmcheck=$?
  cnsversion=$(check_schema_version "${DB_HOST}" "${DB_PORT}" "${DB_USER}" "${DB_PASS}" "${DPNS_DB}" "schema_version" "${cnsv}")
  cnscheck=$?

  if [ $dpmcheck -eq 0 ] && [ $cnscheck -eq 0 ]; then
    echo "No upgrades needed - same schema version (${DPM_DB} at ${dpmversion}, ${DPNS_DB} at ${cnsversion})"
    return 0
  fi

  ls /usr/share/dmlite/dbscripts/upgrade/dpm-db-[0-9][0-9][0-9]-to-[0-9][0-9][0-9].sql &> /dev/null
  dpmupdate=$? # $(($?==0))
  ls /usr/share/dmlite/dbscripts/upgrade/cns-db-[0-9][0-9][0-9]-to-[0-9][0-9][0-9].sql &> /dev/null
  cnsupdate=$? # $(($?==0))

  if [ $dpmupdate -eq 0 ] && [ $cnsupdate -eq 0 ]; then
    echo "No upgrades needed - no sql update files"
    return 0
  fi

  dpmupgradeOK=0
  dpnsupgradeOK=0

  # Stop the services
  upgrade_stop_services

  # Store password
  passfile=`mktemp /tmp/dpm_upgrade.XXXXXX`
  echo "$DB_PASS" > $passfile

  # Change working directory
  cd /usr/share/dmlite/dbscripts/upgrade/ &> /dev/null

  if [ $dpmupdate -eq 0 ];then
    # Update DPM Schema
    for file in `ls dpm-db-[0-9][0-9][0-9]-to-[0-9][0-9][0-9].sql 2> /dev/null`; do
      fromv=`echo $file | cut -d - -f 3`
      tov=`echo $file | cut -d - -f 5 | cut -d . -f 1`
      if [ $dpmupgradeOK -eq 0 ] && [ $tov -gt $dpmversion ]; then
        echo "Upgrading DPM schema from $fromv to $tov with $file"
        mysql -h "${DB_HOST}" -P "${DB_PORT}" -u "${DB_USER}" --pass="${DB_PASS}" -D "${DPM_DB}" < "$file"
        if [ $? -eq 0 ]; then
          dpmversion=$tov
        else
          echo "Error upgrading DPM schema"
          dpmupgradeOK=1
        fi
      fi
    done
  fi

  if [ $cnsupdate -eq 0 ]; then
    # Update DPNS Schema
    for file in `ls cns-db-[0-9][0-9][0-9]-to-[0-9][0-9][0-9].sql 2> /dev/null`; do
      fromv=`echo $file | cut -d - -f 3`
      tov=`echo $file | cut -d - -f 5 | cut -d . -f 1`
      if [ $dpnsupgradeOK -eq 0 ] && [ $tov -gt $cnsversion ]; then
        echo "Upgrading DPNS schema from $fromv to $tov with $file"
        mysql -h "${DB_HOST}" -P "${DB_PORT}" -u "${DB_USER}" --pass="${DB_PASS}" -D "${DPNS_DB}" < "$file"
        if [ $? -eq 0 ]; then
          cnsversion=$tov
        else
          echo "Error upgrading DPNS schema"
          dpnsupgradeOK=1
        fi
      fi
    done
  fi

  # Return to previous directory
  cd - &> /dev/null

  # Remove password
  rm -f ${passfile}

  # Restart
  upgrade_start_services

  if [ $dpmupgradeOK -ne 0 ] || [ $dpnsupgradeOK -ne 0 ]; then
    return 1
  else
    echo "Schema up to date"
    return 0
  fi
}


function parse_config_user () {
  CONFIG_FILE=$1
  DEFAULT=$2
  ret=$(head -n 1 "${CONFIG_FILE}" 2> /dev/null | sed 's|/.*||')
  if [ "${ret}" != "" ]; then
    echo "${ret}"
  else
    echo "${DEFAULT}"
  fi
}

function parse_config_pass () {
  CONFIG_FILE=$1
  DEFAULT=$2
  ret=$(head -n 1 "${CONFIG_FILE}" 2> /dev/null | sed 's|[^/]*.||;s|\(.*\)@.*|\1|')
  if [ "${ret}" != "" ]; then
    echo "${ret}"
  else
    echo "${DEFAULT}"
  fi
}

function parse_config_host () {
  CONFIG_FILE=$1
  DEFAULT=$2
  ret=$(head -n 1 "${CONFIG_FILE}" 2> /dev/null | sed 's|.*@||')
  echo "${ret}" | grep -q '/'
  if [ $? -eq 0 ]; then
    ret=$(echo "${ret}" | sed 's|/.*||')
  fi
  if [ "${ret}" == "" ]; then
    echo "${DEFAULT}"
  else
    echo "${ret}" | grep -q ':'
    if [ $? -eq 0 ]; then
      ret=$(echo "${ret}" | sed 's|:.*||')
    else
      echo "${DEFAULT}"
    fi
  fi
}

function parse_config_port () {
  CONFIG_FILE=$1
  DEFAULT=$2
  ret=$(head -n 1 "${CONFIG_FILE}" 2> /dev/null | sed 's|.*@||')
  echo "${ret}" | grep -q '/'
  if [ $? -eq 0 ]; then
    ret=$(echo "${ret}" | sed 's|/.*||')
  fi
  if [ "${ret}" == "" ]; then
    echo "${DEFAULT}"
  else
    echo "${ret}" | grep -q ':'
    if [ $? -eq 0 ]; then
      ret=$(echo "${ret}" | sed 's|.*:||')
    else
      echo "${DEFAULT}"
    fi
  fi
}

function parse_config_db () {
  CONFIG_FILE=$1
  DEFAULT=$2
  ret=$(head -n 1 "${CONFIG_FILE}" 2> /dev/null | sed 's|.*@||')
  echo "${ret}" | grep -q '/'
  if [ $? -eq 0 ]; then
    ret=$(echo "${ret}" | sed 's|.*/||')
  fi
  if [ "${ret}" != "" ]; then
    echo "${ret}"
  else
    echo "${DEFAULT}"
  fi
}



# default values
dpmv='350'
dpnsv='320'

# read DPM configuration files
if [ -f /usr/etc/DPMCONFIG ]; then
  dpm_user=$(parse_config_user "/usr/etc/DPMCONFIG" "dpm")
  dpm_pass=$(parse_config_pass "/usr/etc/DPMCONFIG" "secret")
  dpm_host=$(parse_config_host "/usr/etc/DPMCONFIG" "$(hostname)")
  dpm_port=$(parse_config_port "/usr/etc/DPMCONFIG" "3306")
  dpm_db=$(parse_config_db "/usr/etc/DPMCONFIG" "dpm_db")
  #echo "${dpm_user} ${dpm_pass} ${dpm_host} ${dpm_port} ${dpm_db}"
fi
if [ -f /usr/etc/NSCONFIG ]; then
  dpns_user=$(parse_config_user "/usr/etc/NSCONFIG" "dpm")
  #dpns_pass=$(parse_config_pass "/usr/etc/NSCONFIG" "secret")
  #dpns_host=$(parse_config_host "/usr/etc/NSCONFIG" "$(hostname)")
  #dpns_port=$(parse_config_port "/usr/etc/NSCONFIG" "3306")
  dpns_db=$(parse_config_db "/usr/etc/NSCONFIG" "cns_db")
  #echo "${dpns_user} ${dpns_pass} ${dpns_host} ${dpns_db}"
fi

# usage information
if [ "$1" == "-h" -o "$1" == "--help" ]; then
  echo "Script for upgrading DPM database schema"
  echo "Default DB config read from /usr/etc/DPMCONFIG and /usr/etc/NSCONFIG"
  echo "Usage: $0 [ db_host [ db_port [ db_user [ db_pass [ dpm_db [ dpns_db [ dpmv [ dpnsv ]]]]]]]]"
  echo "Examples:"
  echo "  $0 [ $(hostname) ${dpm_port} ${dpm_user} ***** ${dpm_db} ${dpns_db} ${dpmv} ${dpnsv} ]"
  echo "  $0 dpmdb.$(hostname --domain) ${dpm_port}"
  echo "  $0 dpmdb.$(hostname --domain) ${dpm_port} ${dpm_user} secret"
  echo "  $0 dpmdb.$(hostname --domain) ${dpm_port} ${dpm_user} secret ${dpm_db}"
  echo "  $0 dpmdb.$(hostname --domain) ${dpm_port} ${dpm_user} secret ${dpm_db} ${dpns_db}"
  echo "  $0 dpmdb.$(hostname --domain) ${dpm_port} ${dpm_user} secret ${dpm_db} ${dpns_db} ${dpmv}"
  echo "  $0 dpmdb.$(hostname --domain) ${dpm_port} ${dpm_user} secret ${dpm_db} ${dpns_db} ${dpmv} ${dpnsv}"
  exit 0
fi

if [ "$#" -gt 0 ]; then
  dpm_host=$1
fi
if [ "$#" -gt 1 ]; then
  dpm_port=$2
fi
if [ "$#" -gt 2 ]; then
  dpm_user=$3
fi
if [ "$#" -gt 3 ]; then
  dpm_pass=$4
fi
if [ "$#" -gt 4 ]; then
  dpm_db=$5
fi
if [ "$#" -gt 5 ]; then
  dpns_db=$6
fi
if [ "$#" -gt 6 ]; then
  dpmv=$7
fi
if [ "$#" -gt 7 ]; then
  dpnsv=$8
fi

upgrade "${dpm_host}" "${dpm_port}" "${dpm_user}" "${dpm_pass}" "${dpm_db}" "${dpns_db}" "${dpmv}" "${dpnsv}"
exit $?
