#!/bin/bash
# Create the mysql gratia summary tables, triggers and stored procedures
# Called automatically by the services.
#
#########################################################################################

TMP=${TMPDIR:-/tmp}/post-install.$$
trap "rm $TMP* 2>/dev/null" EXIT

is_innodb=1

function preprocess_proc() {
    if [[ -z "$is_innodb" ]]; then
        TPROC=`mktemp "$TMP.preprocess.XXXXXXXXXX"`
        if [[ -z "$TPROC" ]]; then
            echo "Unable to create temporary file \"$TMP.preprocess.XXXXXXXXXX\"" 1>&2
            exit 1
        fi
        sed -e 's/[ 	]*ENGINE[ 	]*=[ 	]*'"'"'innodb'"'"'//gi' "$proc" > "$TPROC"
        proc="$TPROC"
     fi
}
dbname=`grep ^service.mysql.url /etc/gratia/services/service-configuration.properties | tr ':' ' ' | tr '/' ' ' | awk '{print $5;}'`
dbhost=`grep ^service.mysql.url /etc/gratia/services/service-configuration.properties | tr ':' ' ' | tr '/' ' ' | awk '{print $3;}'`
dbport=`grep ^service.mysql.url /etc/gratia/services/service-configuration.properties | tr ':' ' ' | tr '/' ' ' | awk '{print $4;}'`
dbpasswd=`grep ^service.mysql.rootpassword /etc/gratia/services/service-authorization.properties | tr '=' ' ' | awk '{print $NF;}'`
if [ "x$dbpasswd" = "x" ] || [ $dbpasswd = "service.mysql.rootpassword" ]
then
    dbpasswd=""
fi

# This would be so much easier if we could guarantee a "drop trigger if
# exists" syntax.
function prepareCountTrigger() {
  local table_name=${1##countTrigger}
  TPROC="${TMP}.countTrigger.${table_name}"
  if [[ "${table_name}" == "DupRecord" ]]; then
    maybe_increment_error_line="  update TableStatistics set nRecords = nRecords + 1 where valueType = 'current' and RecordType = ifnull(new.RecordType,'') and Qualifier = new.error;"
    maybe_increment_error_line_life="  update TableStatistics set nRecords = nRecords + 1 where valueType = 'lifetime' and RecordType = ifnull(new.RecordType,'') and Qualifier = new.error;"
    maybe_decrement_error_line=${maybe_increment_error_line/\+/-}
    maybe_decrement_error_line=${maybe_decrement_error_line//new/old}
    maybe_increment_error_line="  insert ignore into TableStatistics (ValueType,RecordType,Qualifier,nRecords) values ('current',ifnull(new.RecordType,''), new.error, 0),('lifetime',ifnull(new.RecordType,''), new.error, 0);${maybe_increment_error_line}${maybe_increment_error_line_life}"
    maybe_decrement_error_line="  insert ignore into TableStatistics (ValueType,RecordType,Qualifier,nRecords) values ('current',ifnull(old.RecordType,''), old.error, 1);${maybe_decrement_error_line}"
  fi
  cat > "${TPROC}" <<EOF
delimiter ||
drop procedure if exists conditional_trigger_drop;
create procedure conditional_trigger_drop()
begin
  declare mycount int;

-- Old trigger
  select count(*) into mycount from information_schema.triggers where
    trigger_schema = Database()
    and event_object_table = 'JobUsageRecord'
    and trigger_name = 'trigger01';

  if mycount > 0 then
    drop trigger trigger01;
  end if;

-- Previous increment trigger
  select count(*) into mycount from information_schema.triggers where
    trigger_schema = Database()
    and event_object_table = '${table_name}'
    and trigger_name = 'countInc${table_name}';

  if mycount > 0 then
    drop trigger countInc${table_name};
  end if;

-- Previous decrement trigger
  select count(*) into mycount from information_schema.triggers where
    trigger_schema = Database()
    and event_object_table = '${table_name}'
    and trigger_name = 'countDec${table_name}';

  if mycount > 0 then
    drop trigger countDec${table_name};
  end if;
end
||
call conditional_trigger_drop();
||
create trigger countInc${table_name} after insert on ${table_name}
for each row
f:begin
  insert ignore into TableStatistics (ValueType,RecordType,Qualifier,nRecords) values('current','${table_name}','',0);
  update TableStatistics set nRecords = nRecords + 1 where ValueType = 'current' and RecordType = '${table_name}' and Qualifier = '';
  insert ignore into TableStatistics (ValueType,RecordType,Qualifier,nRecords) values('lifetime','${table_name}','',0);
  update TableStatistics set nRecords = nRecords + 1 where ValueType = 'lifetime' and RecordType = '${table_name}' and Qualifier = '';
${maybe_increment_error_line}
end
||
create trigger countDec${table_name} after delete on ${table_name}
for each row
f:begin
  insert ignore into TableStatistics (ValueType,RecordType,Qualifier,nRecords) values('current','${table_name}','',1);
  update TableStatistics set nRecords = nRecords - 1 where ValueType = 'current' and RecordType = '${table_name}' and Qualifier = '';
${maybe_decrement_error_line}
end
EOF

  proc=$TPROC
}

if (( $# == 0 )); then
  set -- "stored"
elif [[ "$*" == *all* ]]; then
  set -- "stored" "summary" "trigger"
fi

while [[ -n "$1" ]]; do
  action="$1"
  shift
  case $action in
      summary)
#        proc="/usr/share/gratia/sql/build-summary-tables.sql"
        set -- "$@" summary-view
        # build-summary-tables.sql removed.
        echo "argument \"summary\" obsolete -- ignored" 1>&2
        continue
        ;;
      stored)
        #proc="/usr/share/gratia/sql/build-stored-procedures.sql"
        set -- "$@" stored-extra-3 stored-1 stored-2 stored-3 stored-4 stored-5
        if [[ `hostname -f` == *.fnal.gov ]]; then
          set -- "$@" proc-edit-permission
        fi
        continue
        ;;
      stored-1)
        # Create trace table and common functions for the reports stored prcedures        
        proc="/usr/share/gratia/sql/reportsGeneral.sql"
        ;;
      stored-2)
        # Reports stored procedure
        proc="/usr/share/gratia/sql/reports.sql"
        ;;
      stored-3)
        # Ranked Reports stored procedure
        proc="/usr/share/gratia/sql/reportsRanked.sql"
        ;;
      stored-4)
        # PSACCT Reports stored procedure
        proc="/usr/share/gratia/sql/reportsPSacct.sql"
        ;;
      stored-5)
        # PSACCT Reports stored procedure
        proc="/usr/share/gratia/sql/build-osgdaily-stored-procedures.sql"
        ;;
      stored-extra-1)
        # Hand-tweaked procedure (temporary)
        #proc="/usr/share/gratia/sql/WeeklyUsageByVORanked.sql"
        # WeeklyUsageByVORanked.sql removed.
        echo "stored procedure \"WeeklyUsageByVORanked.sql\" obsolete -- ignored" 1>&2
        continue
        ;;
      stored-extra-2)
        # Hand-tweaked procedure (temporary)
        #proc="/usr/share/gratia/sqlSiteUsageCountByVO.sql"
        # SiteUsageCountByVO.sql removed.
        echo "stored procedure \"SiteUsageCountByVO.sql\" obsolete -- ignored" 1>&2
        continue
        ;;
      stored-extra-3)
        # Hand-tweaked procedure (temporary)
        proc="/usr/share/gratia/sql/dCacheSimple.sql"
        ;;
      static-reports)
        # For CSV static reports
        #proc="/usr/share/gratia/sql/static-report-procedures.sql"
        # static-report-procedures.sql removed.
        echo "stored procedure \"static-report-procedures.sql\" obsolete -- ignored" 1>&2
        continue
        ;;
      trigger)
        proc="/usr/share/gratia/sql/build-trigger.sql"
        set -- "$@" summary-procedures services-summary-procedures tablestatistics-summary-procedures backlogstatistics-summary-procedures
        ;;
      summary-procedures)
        proc="/usr/share/gratia/sql/summary-procedures.sql"
        ;;
      services-summary-procedures)
        proc="/usr/share/gratia/sql/services-summary-procedures.sql"
        ;;
      tablestatistics-summary-procedures)
        proc="/usr/share/gratia/sql/tablestatistics-summary-procedures.sql"
        ;;
      backlogstatistics-summary-procedures)
        proc="/usr/share/gratia/sql/backlogstatistics-summary-procedures.sql"
        ;;
      ps)
#        proc="/usr/share/gratia/sql/build-ps-node-summary-table.sql"
        echo "argument \"ps\" obsolete -- ignored" 1>&2
        continue;
        ;;
      summary[-_]view)
        proc="/usr/share/gratia/sql/build-summary-view.sql"
        ;;
      countTrigger*)
        prepareCountTrigger $action
        ;;
      proc-edit-permission)
        proc="/usr/share/gratia/sql/proc-edit-permission.sql"
        ;;
      *)
        echo "Unrecognized action \"$action\"" 1>&2
        exit 1
  esac

  tmpfile=/tmp/.post_install.$$   # very temporary passwd file
  if [[ -r "${proc}" ]]; then
    printf "post-install: loading $proc ... "
    preprocess_proc
    #--- create temporary password file ---
    cat >$tmpfile <<EOF
[client]
password="$dbpasswd"
EOF
    chmod 600 $tmpfile
    #--- do it -----
   cat ${proc} | mysql --defaults-extra-file=$tmpfile -B --unbuffered --user=root  --host=$dbhost --port=$dbport $dbname 
   status=$?
    #--- remove temporary password file ---
    rm -f $tmpfile
  else
    echo "$proc is not readable!" 1>&2
    status=1
  fi
  if (( $status != 0 )); then
    echo "FAILED with status $status" 1>&2
    exit $status
  else
    echo "OK"
  fi
done
