#!/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! This is overkill now as links are completely dynamic now, but
# it does keep us from regenerating the link order if it's not necessary and
# somebody just runs the script blindly.

# 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}"

# Fingure out which runlevels will be modified and only regenerate the link
# order on those runlevels.
get_default_start
get_default_stop


########### I stopped here as I was bored.  I'll dig a little deeper later, but
########### basically, I need to grep through the fullheaders in a for loop for
########### the value of scriptcount, and then find services started in each 
########### runlevel that is listed in defaultstart for the script that is
########### being installed.  For each runlevel, reorder the scripts and make
########### a special case to ensure that a required or should start is/is not
########### in sysint.  By defualt, use increments of 5 unless the total
########### number of scripts run in a given runlevel exceeds 20, if so, then
########### divide 100 by the number of scripts and use the whole number value
########### as the numerical separater for link names.  Also, remove all
########### existing links that point to an LSB scipt in the specified runlevel
########### directory before placing the new ones...but don't screw with
########### links that point to non LSB compliant scripts.

## Figure out 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!




