#!/bin/bash

### BEGIN INIT INFO
# Provides: Geolane Gateway Startscript
# Required-Start:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Starts the Gateway
# Description: Starts the Gateway.
### END INIT INFO

# SETTINGS
####################################

USERNAME='geoUpdate'
COPATH='/home/ftpserver/apacher-ftpserver'
ID='GeoUpdate'
COMMAND='./bin/ftpd.sh res/conf/ftpd-geolane.xml'
SERVICE='ftpd.sh'

# functions
####################################

ME=`whoami`
as_user() {
  if [ $ME == $USERNAME ] ; then
    bash -c "$1"
  else
    su - $USERNAME -c "$1"
  fi
}

start() {
  echo -e "${Y}Starting ${B}$ID ${Y}...${D}"

  if status; then
    echo -e "${R}Error: ${B}$ID ${R}is already running!${D}"
    exit 1
  fi

  cd $COPATH
  as_user "cd $COPATH && screen -dmS $ID $COMMAND"
}

stop() {
  echo -e "${Y}Stopping ${B}$ID ${Y}...${D}"

  if ! status; then
    echo -e "${R}Error: ${B}$ID ${R}is not running!${D}"
  exit 1
  fi

  as_user "screen -S $ID -p 0 -X kill"
  echo -e "${G}Shutting down ...${D}"
}

statustext() {
  if status; then
    echo -e "${B}$ID ${G}is running ${B}${D}"
  else
    echo -e "${B}$ID ${R}is not running!${D}"
  fi
}

status() {
  pgrep -u $USERNAME -f $SERVICE > /dev/null
}

attach() {
  if ! status; then
    echo -e "${R}Error: ${B}$ID ${R}is not running!${D}"
    exit 1
  fi
  as_user "screen -S $ID -r"
}

# parameter parsing
####################################

case "$1" in

  start)
    start
    sleep 2
    statustext
  ;;

  stop)
    stop
    sleep 2
    statustext
  ;;

  restart)
    stop
    start
    statustext
  ;;

  status)
    statustext
  ;;

  attach)
    attach
  ;;

  *)
    echo -e "${Y}Usage: $0 {${G}start${Y}|${R}stop${Y}|${B}restart${Y}|${B}status${Y}|${B}attach${Y}} ${Y}[ID]${D}"
    echo -e "${Y}While attached press ${B}ctrl-a crlt-d ${Y}to stop watching without stopping the server!"
    exit 1
  ;;

esac