#!/bin/sh
# WARNING: This file was auto-generated. Do not edit!
conf_bin='/usr/bin'
echon() {
  echo -n "$*"
}
set -e
PATH="/bin:/usr/bin:/usr/local/bin:$PATH"
export PATH
program=`basename $0`

warn() {
  echo "$program: Warning: $@" >&2
}

fatal() {
  echo "$program: Fatal error: $@" >&2
  exit 1
}

usage_nocd() {
  min=$1; max=$2; opts=$3; msg=$4; shift 4

  while getopts q$opts flag; do
    case $flag in
      q)
        exec >/dev/null
	;;
      \? | :)
        exit 1
	;;
      ?)
        eval "opt_${flag}=true"
	;;
    esac
  done

  shift=$(( $OPTIND - 1 ))
  shift $shift

  if [ $# -lt $min -o $# -gt $max ]; then
    echo "$0: usage: $program [-q] $msg" >&2
    exit 1
  fi
}

usage() {
  usage_nocd "$@"
  cd "$SVSCANDIR"
}

SVSCANDIR="${SVSCANDIR-/service}"
SVCLOCKDIR="${SVCLOCKDIR-/var/service}"
set -e

filename="${1-/etc/inittab}"

# Look for the svscan lines, and exit if they both exist

SV_pattern='^SV:.*svscan-start'
SX_pattern='^SX:.*svscan-stopall'
if egrep "$SV_pattern" "$filename" >/dev/null 2>&1 &&
   egrep "$SX_pattern" "$filename" >/dev/null 2>&1
then
  echo "$0: Nothing to do:"
  echo "  '$filename' appears to already have the svscan lines in it."
  exit 0
fi

# Set up variables for a backup copy of the inittab, and a temporary
# output file.

date=`date +%Y-%m-%d`
backup="$filename-$date"
if [ -e "$backup" ]; then
  echo "$0: Backup file '$backup' already exists."
  exit 1;
fi

tmpfile="${filename}.tmp.$$"
if [ -e "$tmpfile" ]
then
  echo "$0: Temporary file '$tmpfile' already exists."
  exit 1
fi

catit() { cat "$filename" | egrep -v "$SV_pattern" | egrep -v "$SX_pattern"; }

# Insert the two svscan lines between the first rc line and the rest of
# the inittab so that svscan gets executed before the rc# scripts do.

# First, find the target pattern
lineno=`catit | egrep -n '^[^:]*:0:wait:.*rc' | cut -d: -f1 | head -n 1`
if [ -z "$lineno" ]
then
  echo "$0: Couldn't find the search line in '$filename'."
  exit 1;
fi

# Pre-create the temporary file
if ! touch "$tmpfile" >/dev/null 2>&1
then
  echo "$0: Could not create the temporary output file '$tmpfile'"
  exit 1
fi

# Splice the new lines into the old file
{
  catit | head -n $(($lineno-1))
  echo "SV:2345:respawn:$conf_bin/svscan-start /service"
  echo "SX:S016:wait:$conf_bin/svscan-stopall /service"
  catit | tail -n +$lineno
} >"$tmpfile"

# And move it over the existing file
ln "$filename" "$backup"
mv -f "$tmpfile" "$filename"
