#!/bin/sh

#
# NAME
#  clpdb2still
#
# DESCRIPTION
#  Execute still point command for DB2
#
# USAGE
#   Suspend:
#     clpdb2still -d <database name> -u <user name> -s
#   Resume:
#     clpdb2still -d <database name> -u <user name> -r
#

err_db=2
err_user=2
err_oper=2
err_args=2
err_suspend=5
err_resume=6
ret_oper=0

function printUsage() {
  echo "USAGE"
  echo "  Suspend:"
  echo "    clpdb2still -d <database name> -u <user name> -s"
  echo "  Resume:"
  echo "    clpdb2still -d <database name> -u <user name> -r"
  echo " "
}

function checkParamValue() {
  if [ -z "$1" ] || [ "-" = "${1:0:1}" ]; then
    echo " "
    echo "Error:" "$2"
    echo " "
    exit $3
  fi
}

function suspendDatabase() {
  su -l -c "db2 \"CONNECT TO $1\" && db2 \"SET WRITE SUSPEND FOR DATABASE INCLUDE LOGS\" && db2 \"COMMIT\" && db2 \"DISCONNECT $1\"" "$2"
  ret_oper=$?
  if [ $ret_oper -ne 0 ]; then
    echo " "
    echo "Error: suspend command return code =" $ret_oper
    echo " "
    exit $err_suspend
  fi
}

function resumeDatabase() {
  su -l -c "db2 \"CONNECT TO $1\" && db2 \"SET WRITE RESUME FOR DATABASE\" && db2 \"COMMIT\" && db2 \"DISCONNECT $1\"" "$2"
  ret_oper=$?
  if [ $ret_oper -ne 0 ]; then
    echo " "
    echo "Error: resume command return code =" $ret_oper
    echo " "
    exit $err_resume
  fi
}

#
# main process
#

# check arguments
if [ -z "$1" ]; then
  printUsage
  exit 0
fi

# get options and set parameters
dbname=""
username=""
operation=""
while [ -n "$1" ]
do
  case "$1" in
  -d)
    shift; checkParamValue "$1" "invalid database name" $err_db
    dbname="$1"
    #echo "database name =" "$dbname"
    ;;
  -u)
    shift; checkParamValue "$1" "invalid user name" $err_user
    username="$1"
    #echo "user name =" "$username"
    ;;
  -s)
    operation="suspend"
    #echo "operation =" "$operation"
    ;;
  -r)
    operation="resume"
    #echo "operation =" "$operation"
    ;;
  *)
    echo " "
    echo "Error: invalid argument =" "$1"
    echo " "
    exit $err_args
    ;;
  esac
  shift
done

# check value of parameters
checkParamValue "$dbname" "missing database name" $err_db
checkParamValue "$operation" "missing operation '-s' or '-r'" $err_oper
checkParamValue "$username" "missing user name" $err_user

# execute operation
case "$operation" in
suspend)
  suspendDatabase "$dbname" "$username"
  ;;
resume)
  resumeDatabase "$dbname" "$username"
  ;;
esac

exit 0
