#!/bin/bash
# daemon.sh v0.5
#############################################################################################
# Author:   Øyvind "Mr.Elendig" Heggstad <heggstad@har-ikkje.net>                           #
#                                                                                           #
# A script to view/controll the status                                                      #
# of the daemons in rc.d                                                                    #
#                                                                                           #
# Warning: This script will probably mess up                                                #
# both your install and your life                                                           #
#                                                                                           #
# Released under GPLv2  (Yea, I know I need to include it, but I'm to lazy)                 #
#                                                                                           #
#############################################################################################

#### ToDo ####
# Ubuntufy it (add colours and other fancy stuff)
# Test it for bugs
# Clean up
# Comments ftw
# + lots of other stuff

### Colours!! ###

C_STOPPED="\033[0;31m" # red
C_RUNNING="\033[0;32m" # green
C_RESET="\033[m"

#### functions ####

# Something phailed! (thanks bruenig for the idea)
err () {
    echo "$1"
    exit 1
} 

# List the status of the daemons
daemon_status () {
    daemons=( /etc/rc.d/* )
    if [ -z "$1" ]; then
	for d in ${daemons[@]##*/}; do
	    if [ -f "/var/run/daemons/$d" ]; then
		printf "%-30b%-10b\n" ${d} ${C_RUNNING}RUNNING${C_RESET}
	    else
		printf "%-30b%-10b\n" ${d} ${C_STOPPED}STOPPED${C_RESET}
	    fi
	done
    else
	[ ! -f "/etc/rc.d/$1" ] && err "No sutch daemon"
	if [ -f "/var/run/daemons/$1" ]; then
	    printf "%-30b%-10b\n" ${1} ${C_RUNNING}RUNNING${C_RESET}
	else
	    printf "%-30b%-10b\n" ${1} ${C_STOPPED}STOPPED${C_RESET}
	fi
    fi

}

# Start/stop/restart a daemon
daemon_controll () {
    [ "$UID" -ne "0" ] && err "You must be root to ""$1"" a daemon" # no root, no fun
    case "$1" in
	"start" | "stop" | "restart" )
	    [ ! -f "/etc/rc.d/$2" ] && err "No sutch daemon"
	    eval /etc/rc.d/$2 $1
	    ;;
	* ) 
	    err  "Invalid option" 
	    ;;
    esac
}

# Usage
usage () {
    echo "Usage:"
    echo "      start|stop|restart <daemon>  Starts|Stops|Restarts a daemon."
    echo "      status <daemon>              Shows the status of the daemon."
    echo "                                   ( if daemon is obmitet, the status"
    echo "                                   of every daemon will be listed).|"
}

#### The main thing ####

case "$1" in
    "start" | "stop" | "restart" ) daemon_controll $1 $2 ;;
    "status" ) daemon_status $2 ;;
    * ) usage ;;
esac

