#! /bin/bash
#
# stm-counters.sh
#
# A script to run a well-defined number of commands,
# to check admin tools that will report this number.

#### Arguments

get_arguments() {
  while [ -n "$1" ]
  do
    case $1 in
      --sleep ) SLEEP="0.$2"
                shift ;;
      * )       echo "Unknown argument '$1' - abort"
                exit 1 ;;
      esac
    shift
  done
}

#### Create a test table

create_tab() {
  mysql -u joerg -pjoerg <<eoc
    use test
    drop table if exists stm_count;
    create table stm_count (
      id int auto_increment,
      wann timestamp,
      inhalt varchar(50),
      primary key (id),
      key (wann)
    ) engine = InnoDB;
eoc
}

#### Load initial data

load_tab() {
  mysql -u joerg -pjoerg -e "show create table test.stm_count \G" --table

  CNT=1000
  while [ "$CNT" -gt 0 ]
  do
    echo "insert into stm_count (inhalt) values ('Countdown $CNT');"
    CNT=`expr $CNT - 1`
  done | mysql -u joerg -pjoerg test

  mysql -u joerg -pjoerg -e "select count(*), min(wann), max(wann) from test.stm_count" --table
}

#### Do the select statements

select_tab() {
  echo "Ready to start the selects? Hit return (<cr>)"
  read DUMMY
  date

  CNT=1
  while [ "$CNT" -le 1000 ]
  do
    echo "select id, sleep($SLEEP) from stm_count where inhalt like '% $CNT';"
    CNT=`expr $CNT + 1`
  done | mysql -u joerg -pjoerg test >/dev/null

  date
}

####
#### MAIN
####

SLEEP=0.1
get_arguments $*
echo "sleep = $SLEEP"

create_tab
load_tab

select_tab

exit 0
