#!/bin/bash
#
# mysql-tunnel
#
# Author: p@entropux.net
# Date: 2013-01-20

NAME='mysql-tunnel'

LANG=C
RETVAL=0

SOURCE_FILE="/etc/default/$NAME"
if [ ! -f "$SOURCE_FILE" ]; then
  echo "Source file not found ($SOURCE_FILE)."
  exit 1
fi

. "$SOURCE_FILE"

if [ -z "$PIDFILE" ]; then
  echo 'PIDFILE variable not sourced.'
  exit 1
fi
if [ -z "$SSH_SESS" ]; then
  echo 'SSH_SESS variable not sourced.'
  exit 1
fi
if [ -z "$SSH_USER" ]; then
  echo 'SSH_USER variable not sourced.'
  exit 1
fi

running_pid()
{
  pgrep -U "$SSH_USER" -x -f "ssh -f -N $SSH_SESS"
}

# See how we were called.
case "$1" in
  start)
    # already running?
    if pid_list="$(running_pid)"; then
      echo -E "$NAME already running as pid $pid_list"
      exit 1
    fi

    # make sure that sudo works for user
    USER_TEST="$(sudo -u "$SSH_USER" whoami)"
    if [ "$USER_TEST" != "$SSH_USER" ]; then
      echo -E "sudo not functional for user ($SSH_USER)."
      exit 1
    fi

    # start it
    if ! sudo -u "$SSH_USER" ssh -f -N "$SSH_SESS"; then
      echo -E "Unable to start $NAME"
      exit 1
    fi

    echo -E "$NAME started."

    # write pid to file
    pid="$(running_pid)"
    echo -E "$pid" > "$PIDFILE"

    ;;

  stop)
    pid_list="$(running_pid)"
    if [ -z "$pid_list" ]; then
      echo -E "$NAME not running."
      exit 0
    fi

    for pid in $pid_list; do
      echo -E "Gracefully terminating pid $pid ..."
      kill $pid
    done

    sleep 1

    pid_list="$(running_pid)"
    if [ -z "$pid_list" ]; then
      echo -E "$NAME successfully stopped."
      exit 0
    fi

    for pid in $pid_list; do
      echo -E "Forcefully terminating pid $pid ..."
      kill $pid
    done

    sleep 1

    pid_list="$(running_pid)"
    if [ -z "$pid_list"	]; then
      echo -E "$NAME successfully stopped."
      exit 0
    else
      echo -E "$NAME still running as pid $pid_list"
      exit 1
    fi    

    ;;

  status)
    pid_list="$(running_pid)"
    if [ -n "$pid_list" ]; then
      echo -E "$NAME running as pid $pid_list"
      exit 0
    else
      echo -E "$NAME not running."
      exit 1
    fi

    ;;

  restart)
    $0 stop || exit $?
    $0 start || exit $?

    ;;

  *)
    echo "Usage: $0 {start|stop|status|restart}"
    exit 1

esac
