#!/bin/bash
#
################################################################
#
# Should keep this very simple as we do not know what binaries
# are available on the destination system.  Many helper procs
# are used to avoid relying on 'sed' and 'ps'.
#
# For example:
#   ps ax 2>/dev/null | grep '[ /]httpd-tt.tcl'
# is replaced with:
#   grep -l '[ /]httpd-tt.tcl' /proc/[0-9]*/cmdline
#
################################################################

################################################################
#
# The following could be changed from 2916352 to 3244032 if
# we start having memory issues again (BlockFailure's)
#
################################################################
export TIVOSH_POOLSIZE=2916352

shopt -s extglob
dir=${0%%+([^/])}
bin=${dir}httpd-tt.tcl
arc=`uname -m`

# [spitfires Jul 2012] - fix for relative paths causing spurious config directories to be created
dir=`cd $dir; pwd`/

[ -x ${dir}bin_$arc/setpri ] && ${dir}bin_$arc/setpri ts 0 $$

# locate data dir... default to /var/TWP if necessary
#
##################### -- BTUx9

if [ "$TWP_DATA_DIR" = "" ] ; then
  if [ -d /var/TWP ] || ! ( [ -L $dir/config ] || (echo 1 > $dir/.rwtest) 2>/dev/null ) ; then
    export TWP_DATA_DIR="/var/TWP"
  else
    #20120805 - jkozee - remove the trailing slash because only http.itcl expects, everything else adds it 
    #export TWP_DATA_DIR="$dir"
    export TWP_DATA_DIR="${dir%/}"
    rm -f $dir/.rwtest
  fi
fi

################################################################
#
# This will return the value of a configuration parameter
#
################################################################
get_config() {
  grep -i "^$1" $2 |\
  while read lhs eq rhs; do
    # [spitfires Jun 2012] - need to strip CR chars which may be present
    #        echo "${rhs//\"/}"
    echo `echo "${rhs//\"/}"  | tr -d '\r' `
  done
}

################################################################
#
# This is an alternative to using 'ps'
#
################################################################
ps_httpd() {
  grep -l '[ /]httpd-tt.tcl' /proc/[0-9]*/cmdline 2>/dev/null
}

################################################################
#
# Return the status of the daemon
#
################################################################
status() {
  if [ -n "`ps_httpd`" ] ; then
    echo "An httpd is running"
  else
    echo "An httpd is not running"
  fi
}

################################################################
#
# Start the http daemon
#
################################################################
start() {
  export console=$1
  if [ -n "`ps_httpd`" ] ; then
    echo "Warning: An http server was already running"
  fi

  if [ ! -f $bin ] ; then
    echo "Error: could not locate httpd-tt.tcl in dir '${dir}'"
    exit 1
  fi

  if [ ${1:-null} != "console" ] ; then
    if [ -f /var/log/tivoweb.log ] ; then
      mv -f /var/log/tivoweb.log /var/log/Otivoweb.log
    fi
    exec &> /var/log/tivoweb.log
  fi

  # Check to see if there was a crash
  if [ -f /var/twpfailed ] ; then
    # added code to clear the module cache and retry one more time -- BTUx9
    rm $TWP_DATA_DIR/config/module*
    read n </var/twpfailed
    if [ x$n = x ]; then
      n=1
    fi
    if [ $n -lt 2 ]; then
      let n=n+1
      echo $n >/var/twpfailed
    else
      rm /var/twpfailed
      echo "Error: The last session did not complete successfully"
      echo "  Exiting to prevent possible reboot loop"
      echo "  Please check the logs and rerun tivoweb when the problem is fixed"
      echo "If your error pertains to dyncfg, running 'tivoweb dynclear' will reset dyncfg to default"
      exit 1
    fi
  else
    echo 1 > /var/twpfailed
  fi

  # Attempt to remove files froom older distributions
  (cd "$dir" && bash ./clean_dist.sh)

  echo "Using data dir $TWP_DATA_DIR"

  ################### -- BTUx9
  # Pipe twp output, and kill twp if "Dumping mempool" line is detected
  #
  exec 3>&1
  (/bin/bash -c "echo \$$ >&2 ; exec /tvbin/tivosh $bin $2") 2>&1 >&3 3>&- | {
    read pid
    #~ echo params $1 $2
    echo Starting TWP pid=$pid
    echo $pid >/tmp/twppid
    while read a b c
      do
      savea=$a
      echo ERR: $a $b $c
      if [ x$b == xAssertion -o x$b == xmempool ] ; then
        kill -9 $pid
        break
      fi
    done
    if [ x$savea != xQUIT ] ; then
      echo "Restarting TWP"
      exec ${dir}tivoweb console 1>&3 3>&-
    else
      echo "Shutting Down TWP"
    fi
  } &
}

################################################################
#
# Stop the http daemon
#
################################################################
stop() {
  conf=$TWP_DATA_DIR/config/tivoweb.cfg
  if [ ! -s "$conf" ]; then
    conf=${dir}.dist/tivoweb.cfg
  fi

  if [ -f $conf ] ; then
    pass=$(get_config Password $conf)
    user=$(get_config UserName $conf)
    port=$(get_config Port     $conf)
    pref=$(get_config Prefix   $conf)

    # Ensure the loopback interface is up
    ifconfig lo 127.0.0.1 up >/dev/null 2>&1
    addr=127.0.0.1

    if [ -n "$pref" ]; then
      pref="$pref/"
    fi
    if [ -n "$user" ]; then
      url="http://$user:$pass@$addr"
    else
      url="http://$addr"
    fi
    if [ -n "$port" ]; then
      url="${url}:$port"
    fi

    # Check to see if an http daemon is running
    ps_cnt=`ps_httpd | grep -c ""`
    if [ $ps_cnt -ge 1 ] ; then
      # Setup the PATH environment variable
      PATH=/devbin:/bin:/sbin:/tvbin:/var/hack/bin:/tivobin:$PATH

      # Attempt to quit tivoweb/plus via a wget call
      wget --version >/dev/null 2>&1
      if [ $? -ne 127 ]; then
        if wget --version >/dev/null 2>&1; then
          # We have a GNU wget binary
          wget --tries=2 --timeout=15 -O /dev/null -o /dev/null "$url/${pref}quit$1" &
        else
          # Assume a busybox wget binary
          wget -O- "$url/${pref}quit$1" >/dev/null 2>&1 &
        fi
        # Sleep (for up to 30 seconds) to allow TivoWebPlus to quit
        count=1
        while [ $count -le 12 ] ; do
          count=$(($count+1))
          sleep 3
          new_ps_cnt=`ps_httpd | grep -c ""`
          if [ $new_ps_cnt -lt $ps_cnt ] ; then
            count=99
          fi
        done
        if [ $count -ne 99 ] ; then
          echo "Warning: An http daemon is still running, quit may have failed."
          return
        fi
      else
        echo "ERROR: A wget binary could not be found, and is required"
        echo "       to shutdown the application from the command line."
      fi
    fi
  else
    echo "Error: could not locate tivoweb.cfg in dir '${dir}'"
    exit 1
  fi
}

################################################################
#
# Kill the http daemon, forcing a restart (hopefully)
#
################################################################
force() {
  rm $TWP_DATA_DIR/config/module*
  read pid </tmp/twppid
  echo "attempting to kill pid $pid"
  kill $pid
}

################################################################
#
# Process the command line
#
################################################################
case "$1" in
  stop)    stop;;
  start)   start;;
  force)   force;;
  status)  status;;
  reload)  stop /1 ;;
  restart) stop; start;;
  dynclear) mv -f $TWP_DATA_DIR/config/dyncfg.cfg $TWP_DATA_DIR/backups/.; start;;
  #console) start console;;
  *)       start $*;;
esac
