#!/usr/bin/env bash
#
# Copyright (C) 2003 VA Linux Systems Japan, Inc. All rights reserved.
#
# Usage:
#    update-ultrapossum <configure|remove>
#

set -e

eval `ultrapossum-config init`
trap "eval `ultrapossum-config term`" 0

configure_module() {
  ultrapossum-config module | while read f
  do
    v="ULTRAPOSSUM_MODULE_`echo $f | tr a-z- A-Z_`"
    if test "x$reconfig" = "x" || test "${!v}" = "installed"; then
      $UPDATEDIR/update-$f configure
    fi
  done
}

remove_module() {
  ultrapossum-config module | while read f
  do
    $UPDATEDIR/update-$f remove
  done
}

sanity_module() {
  ultrapossum-config module | while read f
  do
    v="ULTRAPOSSUM_MODULE_`echo $f | tr a-z- A-Z_`"
    if test "${!v}" = "installed"; then
      $UPDATEDIR/update-$f sanity
    fi
  done
}

configure() {
  conftemp=`tempfile`
  chmod 600 $conftemp
  # little evil
  getconfig | grep -v SLAPROOTPW > $conftemp
  if test "$SLAPDCONF" -nt "$SLAPDMASTERCONF" ||
  	! test -f "$CONFSTATUS" || ! diff $CONFSTATUS $conftemp > /dev/null
  then
    sanity_module

#  if test "x$MASTER" = "x$HOST"; then
#    if test -f "$DIRECTORY/$BACKUP.ldif"; then
#      ssh -t $BACKUP "sh -c '
#eval \`ultrapossum-config get SYSCONFDIR\`
#if test "x$ULTRAPOSSUM_PROJECT" = "x"; then
#  cf=\$SYSCONFDIR/ultrapossum.cf
#else
#  cf=\$SYSCONFDIR/projects/$ULTRAPOSSUM_PROJECT
#fi
#ultrapossum-config set \$cf SUFFIX=$SUFFIX MASTER=$MASTER BACKUP=$BACKUP > \$cf.tmp 
#mv \$cf.tmp \$cf
#ULTRAPOSSUM_PROJECT=$ULTRAPOSSUM_PROJECT update-ultrapossum configure'
#"
#    fi
#  fi

    install -d $CONFDIR

    configure_module
    /bin/mv $conftemp $CONFSTATUS
  else
    echo "UltraPossum already configured" 1>&2
    /bin/rm -f $conftemp
  fi

}

remove() {
  remove_module
}

case "x$1" in
	xconfigure)
		configure
	;;
	xreconfigure)
		reconfig=1
		configure
	;;
	xsanity)
		sanity_module
	;;
	xremove)
		remove
	;;
	x)
		echo "Usage: $0 <configure|reconfigure|sanity|remove>" 1>&2
		exit 1
	;;
	x*)
		echo "Unknown argument: $1" 1>&2
		exit 1
	;;
esac

