#!/bin/bash
### BEGIN INIT INFO
# Provides: matchserver
# Required-Start: $mysql $syslog
# Required-Stop: $mysql $syslog
# Default-Start: 2 3 5
# Description: Starts all Play Anywhere daemons
#
# 2011-05-08  Arie            Start bulk match service of Raphael
# 2009-11-10  Rachel          switch sanity checks to use cmts user instead of root
# 2009-10-29  Rachel          work with MEDIA schema on host-DB-media host
# 2009-10-12  D'n             Correct unbound '$1' in start_up()
# 2009-10-11  D'n             SYSTEM NAME uses SYSTEM_IS() from scriptlib; errors use printk
# 07-Dec-08 D'n/Ephraim       Add 'startdisk' param to force starting with disk files
# 17-Sep-08 Menashe           add shutdown of Match Server before startup, to get rid of any temp tables after crash
# 11-Sep-08 Lushi             change /bin/sh to /bin/bash
# 04-Sep-08 D'n Russler       Original
#
### END INIT INFO

. /opt/cm/bin/script_lib.sh

f='playanywhere startup'
MATCH_DIR=/opt/cm/bin/stand_alone_match
export MATCH_DIR
DB_USER=$(cat $MATCH_DIR/db_config/user)
DB_PASS=$(cat $MATCH_DIR/db_config/passwd)
DB_NAME=$(cat $MATCH_DIR/db_config/db_name)

LOG_FILE=/opt/cm/logs/match.log

# this is the number of parallel matchservers which will be started
COUNT=4
if [ "$DB_NAME" != 'MEDIA' ]
then
  COUNT=1
fi

sanity_checks() {
  MYSQL=$( mysql --host="host-DB-media" --user="$DB_USER" --password="$DB_PASS" $DB_NAME -e "SELECT 123 FROM DUAL;" 2>&1 )
  RES=$?
  if [ $RES -ne 0 ]
  then
    msg="Can't connect to $DB_NAME db in mysql -- $MYSQL"
    log_msg "ERROR: $msg"
    printk error -t $f "$msg"
  fi
  return $RES
}

start_up() {
  pushd $MATCH_DIR
  ./shutdownMatchServer.sh -dbname $DB_NAME
# /* Name: */      "Dev" 
  if [ $# -gt 0 ]
  then
    d=$1
  else
    d=
  fi
  SYSTEM=`SYSTEM_IS`
  if false \
    || [ "$SYSTEM" == 'Q-A' ] \
    || [ "$d" == 'disk' ] \

  then
    log_msg starting matchserver with disk tables
    ./startMatchServer.sh -count $COUNT -dbname $DB_NAME
  else
    log_msg "starting matchserver with artists & albums in memory"
    ./startMatchServer.sh -martists -malbums -count $COUNT -dbname $DB_NAME
  fi
  popd > /dev/null

  # If the AsyncQueueRunner1.php already runs - no need to start it
  aqr1_pid=$(ps awx | grep AsyncQueueRunner1.php | grep -v grep | awk '{print $1}')
  if [ -z "$aqr1_pid" ];
  then
    cd /opt/cm/www/web_services/3.5/async
    php AsyncQueueRunner1.php &> /tmp/AsyncQueueRunner.log
  fi
}

shut_down() {
  # Kill all instances of AsyncQueueRunner1.php
  aqr_pid=$(ps awx | grep AsyncQueueRunner1.php | grep -v grep | awk '{print $1}' | head -1)
  while [ -n "$aqr_pid" ];
  do
    echo "Killing AsyncQueueRunner1.php pids: [$aqr_pid]"
    kill "$aqr_pid"
    aqr_pid=$(ps awx | grep AsyncQueueRunner1.php | grep -v grep | awk '{print $1}' | head -1)
  done

  # Wait for all instances of AsyncQueueRecordRunner.php to exit by themselves
  echo -n "Awaiting termination of AsyncQueueRecordRunner.php: "
  while [ 1 ];
  do
    aqrr_pid=$(ps awx | grep AsyncQueueRecordRunner.php | grep -v grep | awk '{print $1}')
    if [ -n "$aqrr_pid" ];
    then
      echo -n "."
      sleep 1
    else
      break
    fi
  done
  echo "Done."

  pushd $MATCH_DIR
  ./shutdownMatchServer.sh -dbname $DB_NAME
  popd > /dev/null
}

test_it() {
  pushd $MATCH_DIR
  ./testMatchServer.sh -dbname $DB_NAME
  popd > /dev/null
}

#----------------------------------------

if [ $# -gt 0 ]
then
  if [ $# -eq 3 -a $1 == "-dbname" ]
  then
    DB_NAME=$2
    param=$3
  else
    param=$1
  fi
else
  param=
fi

case "$param" in
  'startdisk' | \
  'start')
    sanity_checks
    RES=$?
    if [ $RES -ne 0 ]
    then
      exit $RES
    fi

    # SKA: if this is vserver, then always use "startdisk"
    #   as we no need in speed optimizations
    ps awx | grep -v grep | grep --quiet 'udev'
    if [ $? -gt 0 ];
    then
        if [ $param == 'start' ];
        then
            param="startdisk"
        fi
    fi

    if [ $param == 'startdisk' ]
    then
    	disk='disk'
    else
        disk=
    fi
    start_up $disk
    RES=$?
    if [ $RES -eq 0 ]
    then
      log_msg Play Anywhere daemon startup completed
    else
      $msg="ERROR ($RES): ********************** Play Anywhere daemon startup failed *******************"
      log_msg "$msg"
      printk error -t $f "$msg"
    fi
  ;;

  'stop')
    shut_down
    RES=$?
    if [ $RES == 0 ]
    then
      log_msg Play Anywhere daemon shutdown completed
    else
      $msg="ERROR ($RES): ********************** Play Anywhere daemon shutdown failed *******************"
      log_msg "$msg"
      printk error -t $f "$msg"
    fi

  ;;

  'recovery')
    ### This method is used to recover an (presumably crashed) match server
    # 1) confirm that the database is in a good state (tables have content
    #    - especially in case of memory tables)
    #    if not, perform a hard start that loads the tables correctly

    full_reset_necessary=0

    #check whether table matchtracks exits
    TABLES_EXIST=`mysql $DB_NAME --host="host-DB-media" --user="$DB_USER" --password="$DB_PASS" -s -e "SHOW TABLES LIKE 'matchtracks'" | grep -v 'tracks$'`
    if [ -n "$TABLES_EXIST" ];
    then
        Records=$(mysql --host="host-DB-media" --user="$DB_USER" --password="$DB_PASS" $DB_NAME -e "select count(*) from matchtracks;" 2>&1 | tail -1)
        if [ $Records -eq 0 ];
        then
          full_reset_necessary=1
        fi
    else
        full_reset_necessary=1
    fi

    if [ $full_reset_necessary -eq 0 ];
    then
        echo Error: recovery without rebuilding tables is not possible. Can not restart as have no idea whether to use disk or memory based tables
        exit 1
    else
       # 2) stop any match processes that are running
       pushd $MATCH_DIR
       ./shutdownMatchServer.sh --nodb -dbname $DB_NAME

       # 3) start all match processes
       ./startMatchServer.sh --nodbcheck -dbname $DB_NAME
    fi
  ;;

  'status' | 'test')
    test_it
  ;;

  *)
    echo "Usage: $0 { start | startdisk | stop | status | recovery }."
    exit 1
  ;;
esac
exit 0
