#!/bin/sh

# This script edits /etc/inetd.conf to enable or disable a particular service
# by uncommenting or commenting a line.  After editing the file, inetd is sent
# a SIGHUP to re-read the file.

INETD_CONF="/etc/inetd.conf"
TEMP_FILE=/tmp/inetd.conf.$$
LOCK_FILE=/tmp/inetd.conf.lock

SYSLOG_ERR="logger -t $(basename $0) -p USER.ERR"

# -----------------------------------------------------------------------------
print_usage_and_exit()
{
    echo
    echo "$this_script: a helper script for editing $INETD_CONF"
    echo "Usage:"
    echo -e "\t$this_script enable  <service>"
    echo -e "\t$this_script disable <service>"
    echo

    exit 1
}

# -----------------------------------------------------------------------------
exit_on_err()
{
    local rc=$1
    local at_line=$2
    
    if [ "$rc" -ne "0" ] ; then
        $SYSLOG_ERR "failed at line $at_line (rc=$rc)"
        exit "$rc"
    fi
}

# -----------------------------------------------------------------------------
inetd_conf_edit()
{
    local cmd=$1
    local service=$2

    cp $INETD_CONF $TEMP_FILE
    exit_on_err $? $LINENO

    if [ "$cmd" == "enable" ] ; then
        sed -i "/^#${service}[ \t]/s/#${service}/${service}/" $TEMP_FILE
    else
        sed -i "/^${service}[ \t]/s/${service}/#${service}/" $TEMP_FILE
    fi
    exit_on_err $? $LINENO

    mv $TEMP_FILE $INETD_CONF
    exit_on_err $? $LINENO

    killall -q -HUP inetd
}

# -----------------------------------------------------------------------------
wait_for_lock()
{
    local cmd=$1
    local service=$2
    local waitcount=10

    touch $TEMP_FILE
    while ! ln $TEMP_FILE $LOCK_FILE 2>/dev/null; do
        sleep 1
        waitcount=$((waitcount - 1))
        if [ "$waitcount" -eq "0" ] ; then
            $SYSLOG_ERR "\"$cmd $service\" timed out waiting for lock"
            rm -f $TEMP_FILE
            exit 1
        fi
    done
}

# main ------------------------------------------------------------------------
this_script=$(basename $0)
cmd=$1
service=$2

if [ "$#" -ne "2" ] ; then
    echo "ERROR: incorrect parameters"
    print_usage_and_exit
fi

case "$cmd" in

    "enable"|"disable")
        wait_for_lock $cmd $service

        # On exit, clean up after ourselves.
        trap 'rm -f $TEMP_FILE $LOCK_FILE' EXIT

        inetd_conf_edit $cmd $service
        ;;

    *)
        print_usage_and_exit
        ;;

esac

exit 0
