#!/bin/sh
# $Id: config_install.sh 58770 2015-03-31 12:26:18Z pc161604 $
# Copyright 2009 Sun Microsystems, Inc. All rights reserved.

XPLACE_HOLDERS='X%%apachelocation
X%%apacheport
X%%machinename
X%%ttauser
X%%ttagroup
X%%ttalocation'
PLACE_HOLDERS="`echo \"${XPLACE_HOLDERS}\" | sed 's/X%%/%%/'`"

fill_place_holders() {
[ ! -f $1 ] && { echo "$0: $1 does not exist"; exit; }
cp -p $1 $1.orig
sed -e "
s|%%apachelocation|${APACHELOCATION}|g
s|%%apacheport|${APACHEPORT}|g
s|%%machinename|${MACHINENAME}|g
s|%%ttauser|${TTAUSER}|g
s|%%ttagroup|${TTAGROUP}|g
s|%%ttalocation|${INSTDIR}|g
" $1.orig > $1
if [ $? -eq 0 ]; then
    rm $1.orig
else
    echo "Substitution failed: $1"
    mv $1.orig $1
fi
chmod $2 $1
chgrp $TTAGROUP $1
chown $TTAUSER $1
}

#
# Exit codes
#
OK=0
FAIL=1

while [ -n "$1" ]; do
    case "$1" in
    --apachelocation=*)
	APACHELOCATION=`expr "$1" : '[^=]*=\(.*\)'`;;
    --apacheport=*)
	APACHEPORT=`expr "$1" : '[^=]*=\(.*\)'`;;
    --machinename=*)
	MACHINENAME=`expr "$1" : '[^=]*=\(.*\)'`;;
    --ttauser=*)
	TTAUSER=`expr "$1" : '[^=]*=\(.*\)'`;;
    --ttagroup=*)
	TTAGROUP=`expr "$1" : '[^=]*=\(.*\)'`;;
    --instdir=*)
	INSTDIR=`expr "$1" : '[^=]*=\(.*\)'`;;
    esac
    shift
done

DoIfEndIf() {
    awk '$1=="%%IfSGD" && $2=="Full" { state=5; next }
	 $1=="%%IfSGD" && $2=="Secure" { state=6; next }
	 $1=="%%IfSGD" { if (state==0) {state=4} else {++state}; next }
	 $1=="%%EndIfSGD" { if (state<=4) {state=0} else {state=4}; next }
	 substr($1,1,4)=="%%If" { ++state; next }
	 substr($1,1,7)=="%%EndIf" { if (state<=1) {state=0} else {--state}; next }
	 '"$2"' { print }' $1
}

DisableIndexes() {
  awk '$1=="<Directory" {
      state=1
    }
    $1=="</Directory>" {
      if (state==1) print "    Options Indexes"
      state=0
    }
    $1=="Options" && state>0 {
      if (state==1) state=2
      if ($2!="None") {
	printf "%s Indexes\n", $0; next
      }
    }
    {
      print
    }' $1 |
  sed '/^[ 	]*Options[ 	].*Indexes/s/[ 	]Indexes//'
}

mode=750


find "${APACHELOCATION}" -type f -print |
xargs egrep -l "${PLACE_HOLDERS}" |
while read f; do
    [ -n "`egrep '^%%If' ${f}`" ] && {
	# Process %%If/%%EndIf sections
	cp -p ${f} ${f}.$$
	DoIfEndIf ${f}.$$ 'state<4' | DisableIndexes >${f}
	rm -f ${f}.$$ 2>/dev/null
    }
    fill_place_holders "$f" "${mode}"
done

##############################
# End Template Substitutions #
##############################

exit $OK
