#!/bin/bash

############################################################################
#    Copyright (C) 2008 by David                                           #
#    david@dward.us                                                        #
#                                                                          #
#    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, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
###########################################################################



# A script to add the service command found on Red Hat systems to a Debian system or any system that doesnt have it for that matter.
# Created 09-07-2008

SERVICE='/usr/sbin/service'
BASH_SERVICE='/etc/bash_completion.d/service'


function exiting {
echo "$1 Exists already. Exiting ..."
exit 2

}


if [ `whoami` == 'root' ]
then


	if [ -f "$SERVICE" ]
	then 
		exiting $SERVICE 
		
	else

	echo "Adding $SERVICE file ..."
	sleep 1
		(
		cat <<'EOF'
		#!/bin/bash

		set -e

		/etc/init.d/$1 $2 $3
EOF
		) > $SERVICE
		chmod 755 "$SERVICE"
		
	fi
	
	if [ -f "$BASH_SERVICE" ]
	then
		exiting $BASH_SERVICE
	else
	echo "Adding $BASH_SERVICE file ..."
	sleep 1
		(
		cat <<'EOF'
		# a function for the autocompletion of the service command.

_service_fn()
{
  # set some local variables
  local cur prev

  COMPREPLY=()
  cur=${COMP_WORDS[COMP_CWORD]}
  prev=${COMP_WORDS[COMP_CWORD-1]}

  #if only one completion or a option is being requested
  #then complete against various options
  if [ $COMP_CWORD -eq 1 ]; then
    COMPREPLY=( $( compgen -W "$(ls /etc/init.d)" $cur ))
  elif [ $COMP_CWORD -eq 2 ]; then
    COMPREPLY=( $( compgen -W "start stop restart pause zap status ineed iuse needsme usesme broken" $cur ))
  else
    COMPREPLY=( $( compgen -f $cur ))
  fi

  return 0
}

#setup the completion
complete -F _service_fn service

EOF
) >$BASH_SERVICE

fi

echo "All completed successfully."


else

	echo "Must be run as root. Exiting..."
	exit 1

fi

