#!/usr/bin/env bash

set -e

# status <pidfile>
status_pid() {
  if test -f $1; then
    if test -d /proc/`head -1 $1`; then
      echo "running"
    else
      echo "stopped"
      echo "W: $1 exist even if pid `head -1 $1` doesn't exist" 1>&2
    fi
  else
    echo "stopped"
  fi
}

wait_pid() {
  if test "`status_pid $1`" = "running"; then
    return 0
  fi

  sleep 1

  if test "`status_pid $1`" = "running"; then
    return 0
  fi

  (for i in 1 2 3 4 5 6 7 8 9 10
  do
    sleep $i
    if test "`status_pid $1`" = "running"; then
      exit 0
    fi
    echo -n "."
  done
  echo "timeout" 1>&2
  exit 1) || exit 1
  echo -n " "
}

stop_pid() {
  if [ -f $1 ]; then
    PID=`head -1 $1`
    if test -d /proc/$PID; then
      kill -TERM $PID 2> /dev/null || true
      sleep 1
      if ! test -d /proc/$PID; then
        if test -f $1; then /bin/rm -f $1; fi
        return 0
      fi
      (for i in 1 2 3 4 5 6 7 8 9 10
      do
        echo -n "." 1>&2
        if ! test -d /proc/$PID; then
          if test -f $1; then /bin/rm -f $1; fi
          exit 0
        fi
        sleep $i
      done
      echo -n " sending KILL signal ($PID)" 1>&2
      kill -KILL $PID 2> /dev/null || true
      sleep 1
      /bin/rm -f $1)
      echo -n " " 1>&2
    else
      echo "W: $1 exist even if pid `head -1 $1` doesn't exist" 1>&2
#      /bin/rm -f $1
    fi
  fi
}

usage() {
  echo "Usage: $0 <status|wait|stop> <pidfile>" 1>&2
  exit 1
}

if test "x$2" = "x"; then
  usage
fi

case "$1" in
  status|wait|stop)
    $1_pid "$2"
    ;;
  *)
    usage
    ;;
esac

