#! /bin/sh
# postinst script for enbd
#
# see: dh_installdeb(1)

#PTB subroutines may fail harmlessly! We don't want set -e
#set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see /usr/doc/packaging-manual/
#
# quoting from the policy:
#     Any necessary prompting should almost always be confined to the
#     post-installation script, and should be protected with a conditional
#     so that unnecessary prompting doesn't happen if a package's
#     installation fails and the `postinst' is called with `abort-upgrade',
#     `abort-remove' or `abort-deconfigure'.

#CONFFILE=/etc/enbd.conf
#INITFILE=/etc/init.d/enbd
SBINDIR=${SBINDIR-/usr/sbin}
PATH=/sbin:/usr/sbin:/bin:/usr/bin

# this function emulates update_inetd in case it isn't on the machine
update_inetd() {

  local pattern=""
  local id="nothing"
  local file=/etc/inetd
  local action=none
  local group=OTHER
  local comment_chars='#<off>#'
  local line=""

  while [ $# -gt 0 ]; do
    case $1 in
      --add)     shift; action=add;     line="$1" ;;
      --remove)  shift; action=remove;  id="$1" ;;
      --enable)  shift; action=enable;  id="$1" ;;
      --disable) shift; action=disable; id="$1" ;;
      --pattern) shift; pattern="$1" ;;
      --file)    shift; file="$1" ;;
      --group)   shift; group="$1" ;;
      --comment-chars) shift; comment_chars="$1" ;;
      *)         return 1 ;;
    esac
    shift
  done

  IFS=','
  set -- $id
  IFS=' '

  case $action in
    add)    
            set -- $line
            id="$1"
            if ! grep -qws "$id" "$file" ; then
              if grep -qws ":${group}:" "$file" ; then 
                sed -e "/$group/a\\
$line
" < $file > $file.new && mv $file.new $file
              else
                cat >>"$file" <<EOF

#:${group}: `echo -n $group | tr '[:upper:]' '[:lower:]'` services
$line
EOF
              fi
            fi
            ;;
    remove) 
            for i; do
              sed -e "/^\\($comment_chars\\)*$i/d" < $file > $file.new \
                  && mv $file.new $file
            done
            ;;
    enable) 
            for i; do
              sed -e "/^\\($comment_chars\\)*$i/s/^\\($comment_chars\\)*//" \
                  < $file > $file.new && mv $file.new $file
            done
            ;;
    disable)
            for i; do
              sed -e "/^$i/s/^/$comment_chars/" < $file > $file.new \
                  && mv $file.new $file
            done
            ;;
  esac
  return 0 
}

# this function emulates which in case /usr/bin is not all there ...
which() {
  IFS=:
  set -- $PATH
  IFS=' '
  for d in $* ; do
    if [ -x $d/$1 ]; then
       echo $d/$1
       return 0
    fi
  done
  return 1
}

# this function emulates start-stop-daemon for other platforms
start_stop_daemon() {

  local action=none
  local executable=""
  local pidfile=""
  local user=""
  local name=""
  local signal=TERM
  local retry=""
  local startas=""
  local dotestonly=no
  local oknodo=no
  local quiet=no
  local chuid=""

  while [ $# -gt 0 ]; do
    case $1 in
      --start)       action=start ;;
      --stop)        action=stop  ;;
      --exec|-x)     executable="$1" ;;
      --pidfile|-p)  pidfile="$1" ;;
      --user|-u)     user="$1" ;;
      --name|-n)     name="$1" ;;
      --signal|-s)   signal="$1" ;;
      --retry|-R)    retry="$1" ;;
      --startas|-a)  startas="$1" ;;
      --test|-t)     dotestonly=yes ;;
      --oknodo|-o)   oknodo=yes ;;
      --quiet|-q)    quiet=yes ;;
      --chuid|-c)    chuid="$1" ;;
    esac
    shift
  done

  local noactionreturn=1
  if [ "$oknodo" = yes ]; then
    noactionreturn=0
  fi
  local cmd=""
  if [ "$dotestonly" = yes ]; then
    cmd=echo
  fi

  case "$action" in
    start)
    	if [ -n "$pidfile" ]; then
    	  if [ -s "$pidfile" ]; then
    	    if kill -0 `head -1 "$pidfile"` 2>&1 >/dev/null; then
    	      return $noactionreturn
            fi
    	  fi
    	fi
    	if [ -n "$name" ]; then
    	  if killall -0 "$name" 2>&1 >/dev/null; then
    	    return $noactionreturn
          fi
    	fi
    	if [ -n "$executable" ]; then
    	  if killall -0 `basename "$executable"` 2>&1 >/dev/null; then
    	    return $noactionreturn
          fi
    	fi
    	if [ -n "$startas" ]; then
    	   if [ -n "$chuid" ]; then
    	     $cmd su "$chuid" -c "$startas" &
    	   else
    	     $cmd $startas &
    	   fi
    	   return 0
    	fi
    	if [ -n "$executable" ]; then
    	   if [ -n "$chuid" ]; then
    	     $cmd su -c "$executable" "$chuid" &
    	   else
    	     $cmd $executable &
    	   fi
    	   return 0
    	fi
    	return $noactionreturn
    ;;
    stop)
    	if [ -n "$pidfile" ]; then
    	  if [ -s "$pidfile" ]; then
    	    if ! $cmd kill -"$signal" `head -1 "$pidfile"` 2>&1 >/dev/null; then
    	      return $noactionreturn
            else
              return 0
            fi
    	  fi
    	fi
    	if [ -n "$name" ]; then
    	  if ! $cmd killall -"$signal" "$name" 2>&1 >/dev/null; then
    	    return $noactionreturn
          else
            return 0
          fi
    	fi
    	if [ -n "$executable" ]; then
    	  if ! $cmd killall -"$signal" `basename "$executable"` 2>&1 >/dev/null; then
    	    return $noactionreturn
          else
            return 0
          fi
    	fi
    	return $noactionreturn
     ;;
  esac
  return $noactionreturn
}


set_update_inetd() {
  UPDATE_INETD="`which update-inetd`" || UPDATE_INETD=update_inetd
  [ -n "$UPDATE_INETD" ] || UPDATE_INETD=update_inetd
}
set_inetd() {
  INETD="`which inetd`" || INETD="`which xinetd`" || INETD=""
}
set_start_stop_daemon() {
  START_STOP_DAEMON="`which start-stop-daemon`" \
     || START_STOP_DAEMON=start_stop_daemon
  [ -n "$START_STOP_DAEMON" ] \
     || START_STOP_DAEMON=start_stop_daemon
}

set_update_inetd
set_inetd
set_start_stop_daemon

maybe_add_to_file() {

      local id="$1"
      local file="$2"
      local backup_suffix="${3:-bak}"

      if [ ! -e $file ]; then
        echo "File" $file "does not exist! Cannot modify!";
        return 1
      fi


      grep -qws "$id" $file            && return 1
      [ $file = $file.$backup_suffix ] && return 1

      [ ! -e $file.$backup_suffix ] && cp -p $file $file.$backup_suffix

      local line=""
      if read l; then
          line="$l"
      fi
      while read l; do
          line="$line
$l"
      done
      $UPDATE_INETD --file "$file" --add "$line"
}

if [ -z "$2" ]; then
  BACKUP_SUFFIX=bak
else
  BACKUP_SUFFIX=bak."$2"
fi

restore_newest_prior_backup() {

   local new_version=${2#.*bak.}
   local file="$1"
   local candidates=

   if [ -z "$3" ]; then
     for candidate in $file.bak.*; do
       candidates="$candidates $candidate"
     done
   else
     candidates="$file.$3"
   fi

   for backup in $candidates; do
     if ! [ $file -nt $backup ]; then
       continue
     fi
     local suffix
     eval "suffix=\${backup#${file}.bak.}"
     if [ -n "$suffix" ] && [ "$suffix" -ge "$new_version" ]; then
       continue
     fi
     if [ -z "$latest_backup" ]; then
       latest_backup="$backup"
       continue
     fi
     if [ "$backup" -nt "$latest_backup" ]; then
       latest_backup="$backup"
       continue
     fi
   done

   if [ -z "$latest_backup" ]; then
     return 1
   fi

   mv "$latest_backup" "$file"
}

trapfn() {
      local file="$1"
      echo
      echo 'Received signal.  Aborting configuration of enbd package.'
      echo -n 'Cleaning up...'
      restore_newest_prior_backup "$file" "$BACKUP_SUFFIX"
      echo 'done.'
      echo
}

main() {

  local conffile
  local conffiles
  local signals="1 2 3 15"

  case "$1" in
    configure)

	conffile=/etc/services
        conffiles="$conffiles $conffile"
        trap "trapfn $conffiles 1>&2 2>/dev/null" $signals
        maybe_add_to_file enbd-cstatd $conffile "$BACKUP_SUFFIX" <<EOF
enbd-cstatd 5051/tcp # NBD client statd
EOF

        maybe_add_to_file enbd-sstatd $conffile "$BACKUP_SUFFIX" <<EOF
enbd-sstatd 5052/tcp # NBD server statd
EOF
	conffile=/etc/inetd.conf
        conffiles="$conffiles $conffile"
        trap "trapfn $conffiles 1>&2 2>/dev/null" $signals
        maybe_add_to_file enbd-cstatd $conffile "$BACKUP_SUFFIX" <<EOF
enbd-cstatd stream tcp nowait root $SBINDIR/enbd-cstatd enbd-cstatd
EOF
        maybe_add_to_file enbd-sstatd $conffile "$BACKUP_SUFFIX" <<EOF
enbd-sstatd stream tcp nowait root $SBINDIR/enbd-sstatd enbd-sstatd
EOF
        [ "$INETD" ] && $START_STOP_DAEMON --quiet --stop --signal 1 --oknodo --exec $INETD

	conffile=/etc/xinetd.conf
        conffiles="$conffiles $conffile"
        trap "trapfn $conffiles 1>&2 2>/dev/null" $signals
        maybe_add_to_file enbd-cstatd $conffile "$BACKUP_SUFFIX" <<EOF
service enbd-cstatd
{
  socket_type = stream
  wait        = no
  user        = root
  server      = $SBINDIR/enbd-cstatd
  disable     = no
}
EOF
        maybe_add_to_file enbd-sstatd $conffile "$BACKUP_SUFFIX" <<EOF
service enbd-sstatd
{
  socket_type = stream
  wait        = no
  user        = root
  server      = $SBINDIR/enbd-sstatd
  disable     = no
}
EOF
    trap - $signals
    [ "$INETD" ] && $START_STOP_DAEMON --quiet --stop --signal USR2 --oknodo --exec $INETD
    ;;

    disable) # for testing
	conffile=/etc/inetd.conf
	$UPDATE_INETD --file $conffile --disable enbd-cstatd,enbd-sstatd
	conffile=/etc/xinetd.conf
	$UPDATE_INETD --file $conffile --disable enbd-cstatd,enbd-sstatd
    ;;

    enable) # for testing
	conffile=/etc/inetd.conf
	$UPDATE_INETD --file $conffile --enable enbd-cstatd,enbd-sstatd
	conffile=/etc/xinetd.conf
	$UPDATE_INETD --file $conffile --enable enbd-cstatd,enbd-sstatd
    ;;

    abort-upgrade)
        # we put back the old stuff
        new_version="$2"
        restore_newest_prior_backup /etc/inetd.conf $new_version
        restore_newest_prior_backup /etc/xinetd.conf $new_version
        restore_newest_prior_backup /etc/services $new_version
    ;;
    
    abort-remove)
        in_favour="$2"
        package="$3"
        new_version="$4"
        # mama .. we have to put back the NEW stuff.
        restore_newest_prior_backup /etc/inetd.conf $new_version
        restore_newest_prior_backup /etc/xinetd.conf $new_version
        restore_newest_prior_backup /etc/services $new_version
    ;;
    
    abort-deconfigure)

    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 0
    ;;
  esac
}

main $*

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
