#!/bin/bash

# This file is part of marionnet
# Copyright (C) 2011 Jean-Vincent Loddo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Extracted from the script marionnet_from_scratch on 2011/04/07
# It's a very basic version, suitable to make and test debian packages

set -e

DAEMON=$(type -p marionnet-daemon.native || type -p marionnet-daemon.byte) || {
  echo "Error: neither marionnet-daemon.native nor marionnet-daemon.byte found."
  exit 1
}

function killall_marionnet_daemon {
 ps -u 0 -o pid,cmd | awk '$2 ~ /marionnet-daemon/ {print $1}' | while read pid; do kill -9 $pid; done
}

function is_marionnet_daemon_launched {
 ps -u 0 -o cmd | awk '$1 ~ /marionnet-daemon/ {print $1}' | grep -q 'marionnet-daemon'
}

function pid_of_marionnet_daemon {
 ps -u 0 -o pid,cmd | awk '$2 ~ /marionnet-daemon/ {print $1}' | while read pid; do echo $pid; done
}

case "$1" in
 start)
  if is_marionnet_daemon_launched; then
    echo "The marionnet daemon is already launched."
    exit 0
  else
    echo -n "Starting the marionnet daemon..."
    $DAEMON >/dev/null 2>/dev/null &
  fi
  echo " Ok"
  ;;
 stop)
  echo -n "Stopping the marionnet daemon..."
  killall_marionnet_daemon || true
  echo " Ok"
  ;;
 status)
  if is_marionnet_daemon_launched; then
    PID=$(pid_of_marionnet_daemon)
    echo "The marionnet daemon is running (PID=$PID)."
  else
    echo "The marionnet daemon is stopped."
  fi
  exit 0
  ;;
 *)
  echo "Usage: $1 (start|stop|status)"
  echo "Start or stop the marionnet daemon."
  exit 1
esac
