#!/bin/sh

PROG="${0##*/}" #program name

export LC_ALL=C

print_version()
{
	cat <<EOF
$PROG version @VERSION@

Written by Stanislav Ievlev

Copyright (C) 2003-2004 ALT Linux Team
EOF
	exit
}

print_usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG [options] 

utility to manipulate system services: add, remove, modify

Valid options are:
  -h, --help	display help screen
  -v, --version	display version information
  -l, --list	get list of available services
  -f, --find	check for service existance
  -d, --delete	remove service from startup
  -r, --read	read service information
  -w, --write	write service information

Report bugs to <inger@altlinux.org>
EOF
	[ -n "$1" ] && exit "$1" || exit
}

field()
{
    echo $1|cut -f$2 -d:
}

TEMP=`getopt -n $PROG -o h,v,l:,d:,r:,w:,f: -l help,version,list:,delete:,read:,write:,find: -- "$@"` || print_usage
eval set -- "$TEMP"

service_list()
{
/sbin/chkconfig --list| grep -v "off.*off.*off.*off.*off.*off.*off$" |
			cut -f1 -d' '|sed 's,.*,& r,'
}

while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-v|--version) print_version
			;;
		-l|--list)
			shift;dir=$1;
			service_list;
			;;
		-d|--delete)
			shift;service=$1;
			/sbin/chkconfig --del $service
			;;
		-f|--find)
			shift;service=$1;
			service_list|grep "^$service"
			;;
		-r|--read)
			shift;service=$1;
			[ -f /etc/init.d/$service ] || exit 0
			echo -n "description:"
			cat /etc/init.d/$service|awk '
			BEGIN {FS=":";in_description=0;need_continue=0}
			/#[[:space:]]+description/ { print $2; in_description = 1 }
			/\\$/ {need_continue = 1}
			/#[[:space:]]+[^d].*\\$/ { if (in_description) {print $0} }
			/#[[:space:]]+[^d].*[^\\]$/ {if (in_description && need_continue) {print $0;}; in_description=0; need_continue = 0; }
			'|sed 's,^#[[:space:]]*,,'
			echo -n "runlevels:"
			/sbin/chkconfig --list $service|
			      sed 's,[0-9]:off,,g; s|\([0-9]\):on|\1|g'|
			      sed "s,$service[[:space:]]*,,"|
			      tr -s ' \t' ' '
			echo -n "running:"
			/sbin/service $service status|awk '
			    /running/ {print 1}
			    /stopped/ {print 0}
			'
			;;
		-w|--write)
			shift;service=$1;
			if ! service_list|grep -qs "^$service";then
			    /sbin/chkconfig --add $service
			fi			
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done

