#!/bin/bash
# Begin /lib/lsb/install_initd

. /lib/lsb/initd_functions

## This script is grossly over commented.  It certainly has room to grow, but
## is exactly to spec and meets LFS's requirements as I have defined them.

# First, the program should take exactly one argument, the full path of the
# script only! 
# Check to make sure only one argument is passed, if not exit 2
# This is not defined by LSB, but is consistent with the exit code for
# invalid or excess arguments in init scripts.
if test ! -n "${1}" -o ! -z "${2}"
then
    echo ""
    echo "Invalid or excess arguments!"
    echo "Usage: ${0} /etc/init.d/<scriptname>"
    echo ""
    exit 2
fi

case "${1}" in
    -*)
        echo ""
        echo "Usage: ${0} /etc/init.d/<scriptname>"
        echo ""
        exit 0
    ;;
esac

# Next check to make sure that the script really exists
# If it does not, exit 5. Again this is not defined by the LSB, however, is
# consistent with the exit values for init scripts when the program is not 
# installed.

if test ! -f "${1}"
then
    echo ""
    echo "Script does not exist!"
    echo "Usage: ${0} /etc/init.d/<scriptname>"
    echo ""
    exit 5
fi

# Go ahead and get all the information that is needed from disk in one shot
get_headers

# Now get the array index number for the specified script.
# Also note that the 'filname' variable is set (basename of script), and
# the script is verified that it is LSB compliant.
get_index "${1}"

### Commented out for now so to test the automatic ordering
## If the distro extensions exist, then use them without question and exit 
## successfully!
#get_distro_headers "${1}"
#if test "${?}" -eq "0"
#then
#    get_default_start
#    get_default_stop
#
#    rm /etc/rc*.d/S??"${filename}"
#    rm /etc/rc*.d/K??"${filename}"
#
#    for runlevel in ${defaultstart}
#    do
#        ln -s ../init.d/"${filename}" \
#            /etc/rc"${runlevel}".d/"${distroheaders[1]}${filename}"
#    done
#
#    for runlevel in ${defaultstop}
#    do
#        ln -s ../init.d/"${filename}" \
#            /etc/rc"${runlevel}".d/"${distroheaders[2]}${filename}"
#    done
#
#else
#    echo "This script only supports distro scripts for now..."
#    exit 1
#fi

## Do starting first
## Simply take the Required-Start and Should-Start items and grep
## through the array's provides section to find them.

## When a Required-Start item  is found, find that it's in sysinit, or find
## the start link in runlevel 5, record it, and continue on to the next
## Required-Start item.  If a Required-Start item is not found, then exit
## immediately with an exit status of 1.

get_required_start "${filename}"
count=1
while test ! "${count}" -gt "${scriptcount}"
do
    for facility in $(echo "${requiredstart}")
    do
        echo "${fullheaders[${count}]}" \
            | grep "^# Provides" \
            | grep "${facility}" > /dev/null
        if test "${?}" -eq "0"
        then
            reqlist="${reqlist} ${scriptlist[${count}]}"
        fi
    done
    count=$(( ${count} + 1 ))
done

if test -z "${reqlist}"
then
    echo ""
    echo "Required-Start facility ${facility} was not found!"
    echo ""
    exit 1
fi

startlink="0"
for required in $(echo "${reqlist}")
do
    if test -f /etc/rcsysinit.d/S??"${required}"
    then
        continue
    elif test -f /etc/rc5.d/S??"${required}"
    then
        # Get the start link number
        link=$( ls /etc/rc5.d/S??"${required}" |
                    sed 's@/etc/rc5.d/@@' | sed 's@^S@@' | \
                    sed "s@${required}@@" )
        if test "${link}" -gt "${startlink}"
        then
            startlink="${link}"
        fi
    else
        echo ""
        echo "Required-Start facility ${facility} is not started!"
        echo ""
        exit 1
    fi
done
unset reqlist link count

## When a Should-Start item is found, find that it's in sysinit, or find the
## start link in runlevel 5, record it, and continue on to the next
## Should-Start item.  If a Should-Start item is not found, then simply
## continue on to the next item or create the link based on the recorded 
## value plus half of the difference of the next higher numbered script.

get_should_start "${filename}"
if test ! -z "${shouldstart}"
then
    count=1
    while test ! "${count}" -gt "${scriptcount}"
    do
        for facility in $(echo "${shouldstart}")
        do
            echo "${fullheaders[${count}]}" \
                | grep "^# Provides" \
                | grep "${facility}" > /dev/null
            if test "${?}" -eq "0"
            then
                reqlist="${reqlist} ${scriptlist[${count}]}"
            fi
        done
        count=$(( ${count} + 1 ))
    done

    for required in $(echo "${reqlist}")
    do
        if test -f /etc/rcsysinit.d/S??"${required}"
        then
            continue
        elif test -f /etc/rc5.d/S??"${required}"
        then
            # Get the start link number
            link=$( ls /etc/rc5.d/S??"${required}" |
                        sed 's@/etc/rc5.d/@@' | sed 's@^S@@' | \
                        sed "s@${required}@@" )
            if test "${link}" -gt "${startlink}"
            then
                startlink="${link}"
            fi
        fi
    done
fi
unset reqlist link count

# Now, find the next highest start link
nextscript=$( ls /etc/rc5.d/ | grep -A 1 "S${startlink}" \
                | sed -e "/S${startlink}/d" \
                      -e "s@^S@@" )
nextscriptname=$( echo "${nextscript}" | sed 's@..@@' )
nextlink=$( echo "${nextscript}" | sed "s@${nextscriptname}@@" )
diff=$(( ${nextlink} - ${startlink} ))
add=$(( ${diff} / 2 ))
startlink=$(( ${startlink} + ${add} ))
unset add diff nextlink nextscriptname nextscript

echo "ln -s ../init.d/${filename} /etc/rc5.d/S${startlink}${filename}"

## Finally, we need to check the existing headers for this script's Provides
## facility in the Should-Start headers and verify that the new symlink
## does provide it before the other script.  If it does not, just leave the
## newly created link in place and spit out a warning.  We'll work out how to
## generate new links for multiple scripts in a later version.

    # Skiping this for now!




