#!/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 db - Name of the database for the snapshots to be made of
# reqparam value dbuser - Name of the database user for the snapshots to be made using
# reqparam value interval - Collection interval
# optparam value Suffix - an optional string to append to the name of the log file 
#

# 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 for the snapshots to occur on" > /dev/stderr
  exit 1
fi

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

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

if [ $# -eq 4 ]; then
  SUFFIX=".$4"
fi

START_FLAGS=""

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
    if [ `su - $DBUSER -c "$DB2 list database directory" | grep -i $DB | wc -l` == "0" ]; then
      echo "Database $DB does not exist on this node" > /dev/stderr
      exit 1
    fi
  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 $DB $DBUSER $INTERVAL &" 
    ;;
  print-stop)
    rm $AUTODIR/var/tmp/db2snapshot.$DB.running
    ;;

  report)
    ;;

  postprocess)
    ;;

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