#!/bin/sh
#
# chkconfig like script for DarwinPorts rc scripts
#  - Jason Corley <jcorley1ATncDOTrrDOTcom>
#

# Set up the appropriate variables
action="$1"
conf="/Library/StartupItems/DarwinPortsStartup/prefix.conf"
# Use basename in case someone passes the full path to the service
service=$(basename $2)

# Simple but verbose usage function
usage() {
    echo
    echo "Usage:  $0 [target] appname.sh"
    echo ""
    echo "    $0 enables or disables an application's ability to start"
    echo "    at boot time.  [target] is either enable or disable."
    echo ""
    echo ""
    echo "Example:  $0 enable apache.sh"
    echo ""
    echo "    Will enable the apache service to start at boot time."
    echo ""
    echo "Example: $0 disable apache.sh"
    echo ""
    echo "    Will disable the apache service so that it does not start"
    echo "    at boot time."
    exit 1
}

# Make sure the first argument wasn't a cry for help
if [ "$action" == "help" ] \
   || [ "$action" = "--help" ] \
   || [ "$action" = "--h" ] \
   || [ "$action" = "-h" ]; then
    usage
fi

# Make sure we got the correct number of arguments
if [ ! "$#" -eq 2 ]; then
    usage
fi

# Find out what the proper prefix should be
if [ -r "${conf}" ]; then
    prefix=$(grep -v "^[[:space:]]*#" "${conf}")
else
    prefix="/opt/local"
fi

# Make sure the application startup script exists and is writable
if [ ! -w ${prefix}/etc/rc.d/${service} ]; then
    echo "${prefix}/etc/rc.d/${service} does not exist or is not writable!"
    echo ""
    echo "Check your permissions to make sure that you can write to the file."
    usage
fi

# Make sure the application supports portrc syntax
grep -q disable ${prefix}/etc/rc.d/${service}
if [ "$?" != "0" ]; then
    echo "${prefix}/etc/rc.d/${service} does not support portrc"
    exit 1
fi

# Actually do what we were called to do (finally)
case $action in
    enable)
        tempfoo=$(basename $0)
        TMPFILE=$(mktemp -q /tmp/${tempfoo}.XXXXXX)
        if [ $? -ne 0 ]; then
            echo "$0: Can't create temp file, exiting..."
            exit 1
        fi
        sed 's|^.disable.*|#disable = no|g' ${prefix}/etc/rc.d/${service} > ${TMPFILE}
        mv -f ${TMPFILE} ${prefix}/etc/rc.d/${service}
        chmod 755 ${prefix}/etc/rc.d/${service}
        ;;
    disable)
        tempfoo=$(basename $0)
        TMPFILE=`mktemp -q /tmp/${tempfoo}.XXXXXX`
        if [ $? -ne 0 ]; then
            echo "$0: Can't create temp file, exiting..."
            exit 1
        fi
        sed 's|^.disable.*|#disable = yes|g' ${prefix}/etc/rc.d/${service} > ${TMPFILE}
        mv -f ${TMPFILE} ${prefix}/etc/rc.d/${service}
        chmod 755 ${prefix}/etc/rc.d/${service}
        ;;
    *)
        usage
        ;;
esac

