#!/bin/bash
# This is the script to start and stop the db2snapshot profiler.
#
# reqparam value start|stop|report|postprocess|install Which action you'd like to perform
# reqparam value dbuser - Name of the database user for the snapshots to be made using
# reqparam value interval - Collection interval
# reqparam value db - Name of the database for the snapshots to be made of (one or more)
#

# adapted from oprofile script, Karl Rister

. /etc/autobench.conf || . functions

if [ $# -lt 1 ]; then
  echo "You must specify start, stop, report, postprocess, or install" > /dev/stderr
  exit 1
fi

if [ $# -lt 2 ]; then
  echo "You must specify the name of the database user for the snapshots to be made as" > /dev/stderr
  exit 1
fi

if [ $# -lt 3 ]; then
  echo "You must specify the the interval for the snapshots to be made on" > /dev/stderr
  exit 1
fi

if [ $# -lt 4 ]; then
  echo "You must specify one or more databases for the snapshots to occur on" > /dev/stderr
  exit 1
fi

CMD="$(echo $1 | tr -t A-Z a-z)"
DBUSER=$2
INTERVAL=$3

# figure out the list of databases
shift; shift; shift
DBS=""
until [ -z "$1" ]
do
  DBS="$DBS $1"
  shift
done


function setup_db2()
{
  su - $DBUSER -c id 2>&1 > /dev/null
  if [ ! $? -eq 0 ]; then
    echo "User $DBUSER does not exist" > /dev/stderr
    exit 1
  else
    DB2=`su - $DBUSER -c "which db2"`
    if [ -e "$DB" ]; then
      echo "User $DBUSER cannot execute db2" > /dev/stderr
      exit 1
    fi
    for i in $DBS
    do
      if [ `su - $DBUSER -c "$DB2 list database directory" | grep -i $i | wc -l` == "0" ]; then
        echo "Database $i does not exist on this node" > /dev/stderr
        exit 1
      fi
    done
  fi
}

case $CMD in
  install)
    getcommand db2snapshot_worker
    setup_db2
    ;;

# start/stop aren't actually used in autobench
  start)
    ;;

  stop)
    ;;

  print-start)
    setup_db2
    echo "db2snapshot_worker $DB2 $DBUSER $INTERVAL $DBS &" 
    ;;
  print-stop)
    echo "rm -fv $AUTODIR/var/tmp/db2snapshot.*"
    ;;

  report)
    ;;

  postprocess)
    ;;

  *)
    echo "The first argument must be start, stop, report, postprocess, or install" > /dev/stderr
    echo "The second argument must be the db user with which to take the snapshots" > /dev/stderr
    echo "The third argument must be the interval at which to take the snapshots" > /dev/stderr
    echo "The 4th+ argument(s) must be the name of the database(s)" > /dev/stderr
    ;;
esac
set +x
