#!/bin/bash

# This file is part of Marionnet, a virtual network laboratory
# Copyright (C) 2007-2017  Jean-Vincent Loddo
# Copyright (C) 2007-2017  Université Paris 13

# 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/>.

# Simple starting/stopping script for Buildroot's quagga installation

# Note that we are root:root when this function is called:
function make_var_quagga_dir {
  local TARGET=${1:-"/var/quagga"}
  mkdir -p $TARGET
  chown quagga:quagga $TARGET
}

function start {
 local VARDIR="/var/quagga"
 [[ -d $VARDIR ]] || make_var_quagga_dir $VARDIR
 # --- 
 shopt -s nullglob
 for i in /etc/quagga/{zebra,bgpd,ripd,ospfd,ripngd,ospf6d,isisd}*.conf; do 
  j=$(basename $i); 
  p=${j%.conf}; 
  pidfile=$VARDIR/$p.pid
  if which &>/dev/null $p; then
    eval $p -d -f $i -i $pidfile -z /var/quagga/zserv.api
  fi
 done
}

function stop {
 for i in /etc/quagga/*.conf; do 
  j=$(basename $i); 
  p=${j%.conf}; 
  which &>/dev/null $p && eval killall $p;  
 done
}

function get_port {
  case $1 in
    zebra)   echo 2601;;
    ripd)    echo 2602;;
    ripngd)  echo 2603;;
    ospfd)   echo 2604;;
    bgpd)    echo 2605;;
    ospf6d)  echo 2606;;
    ospfapi) echo 2607;;
    isisd)   echo 2608;;
esac
}

function status {
 TMPFILE=$(mktemp)
 netstat -a -t >$TMPFILE 
 for i in /etc/quagga/*.conf; do 
  j=$(basename $i); 
  p=${j%.conf}; 
  if which &>/dev/null $p; then
    port=$(get_port $p)
    IPv4=$(if [[ -n $port ]] && grep -q  "0.0.0.0:$port" $TMPFILE; then echo "IPv4"; fi)
    IPv6=$(if [[ -n $port ]] && grep -q  ":::$port" $TMPFILE; then echo "IPv6"; fi)
    case "${IPv4}-${IPv6}" in
      IPv4-IPv6) echo -e "$p\r\t running on port $port IPv4/IPv6";;
          IPv4-) echo -e "$p\r\t running on port $port IPv4 only";;
          -IPv6) echo -e "$p\r\t running on port $port IPv6 only";;
              -) echo -e "$p\r\t NOT running";;
    esac
  fi
 done
 rm $TMPFILE
}

# Main:

case "$1" in
  start) start ;;
   stop) stop ;;
   status) status ;;
      *) echo "Usage: $0 {start|stop|status}"
	 exit 1 ;;
esac
