#!/bin/bash
# Copyright (c) 2010 SuSE Linux AG Nuernberg, Germany.
#
# Author: Michal Hrusecky <mhrusecky@suse.cz>
#
### BEGIN INIT INFO
# Provides:       ipv6
# Required-Start: $network $remote_fs
# Required-Stop: $network $remote_fs
# Default-Start:  2 3 5
# Default-Stop:
# Short-Description: Starts ipv6 tunnel
# Description:    Starts Zexos ipv6 tunnel
### END INIT INFO

# Shell functions sourced from /etc/rc.status:
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_failed        set local and overall rc status to failed
#      rc_failed <num>  set local and overall rc status to <num>
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status
. /etc/rc.status

# First reset status of this service
rc_reset

# Return values acc. to LSB for all commands but status:
# 0 - success
# 1 - generic or unspecified error
# 2 - invalid or excess argument(s)
# 3 - unimplemented feature (e.g. "reload")
# 4 - insufficient privilege
# 5 - program is not installed
# 6 - program is not configured
# 7 - program is not running
# 
# Note that starting an already running service, stopping
# or restarting a not-running service as well as the restart
# with force-reload (in case signalling is not supported) are
# considered a success.

pid_file="/var/run/t6_client.pid"
log_file="/var/log/t6_client.log"
exe_file="/usr/sbin/t6_client"

# Helper function which can end with any status
set_return_value() {
	return $1
}

case "$1" in
    start)
  	echo -n "Starting t6_client service "
	/sbin/modprobe tun &> /dev/null
    	/usr/sbin/t6_client -d -f "$pid_file" -l "$log_file"
	$0 status > /dev/null
  	rc_status -v
  	;;

    status)
    	echo -n "Checking for t6_client service: "
	if [ -f "$pid_file" ]; then
		if ! [ -e /proc/version ]; then
			mount -n -t proc proc /proc
			test -e /proc/version || set_return_value 100
		fi
		pid="`cat "$pid_file"`"
		if [ "$pid" ] && [ -d "/proc/$pid" ]; then
			cmd=`cat "/proc/$pid/cmdline" 2> /dev/null`
			exe=`readlink "/proc/$pid/exe" 2> /dev/null`
			if [ "`echo "$exe" | grep "^$exe_file"`" ] || [ "`echo "$cmd" | grep "^$exe_file"`" ]; then
				set_return_value 0
			else
				set_return_value 1
			fi
		else
			set_return_value 1
		fi
	else
		set_return_value 3
	fi
	rc_status -v
  	;;

    stop)
  	echo -n "Stoping service t6_client "
    	if $0 status > /dev/null; then
		kill "`cat $pid_file`" 2> /dev/null
		set_return_value 0
	fi
	rc_status -v
    	;;
    try-restart)
  	"$0" status >/dev/null &&  "$0" restart
  	rc_status
  	;;

    restart|force-reload|reload)
  	echo "Restarting service t6_client "
  	"$0" stop
  	"$0" start
  	rc_status
  	;;

    *)
  	echo "Usage: $0 {start|stop|status|reload|restart|try-restart|force-reload}"
  	exit 1
  	;;
esac
