#!/usr/bin/env bash
#
# Copyright (C) 2003 VA Linux Systems Japan, Inc. All rights reserved.
#
# LICENSE NOTICE
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#

# Usage:
#    update-ultrapossum <configure|remove>
#

# $Id: update-ultrapossum,v 1.10 2004/04/02 02:34:01 taru Exp $

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
}

up_to_date() {
  if test "$SLAPDCONF" -nt "$CONFSTATUS"; then
    return 1
  fi
  find $SYSCONFDIR | while read f
  do
    if test "$f" -nt "$CONFSTATUS"; then
      return 1
    fi
  done || return 1
  return 0
}

configure() {
  conftemp=`tempfile`
  chmod 600 $conftemp
  getconfig | grep -v SLAPROOTPW > $conftemp
  # little evil
  if ! up_to_date ||
  	! 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/cp -p $conftemp $CONFSTATUS
    cat $conftemp > $CONFSTATUS
  else
    echo "UltraPossum already configured" 1>&2
  fi
  /bin/rm -f $conftemp

}

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

