#!/bin/bash

# Environment variables:
#
# GRID_FUNCTIONS
# NORDUGRID_CONFIG
# NORDUGRID_LOCATION
#

GRID_FUNCTIONS=${GRID_FUNCTIONS:-/etc/init.d/grid-functions}
if test ! -r "$GRID_FUNCTIONS"; then
  echo "grid functions ($GRID_FUNCTIONS) not available"
  exit 1
fi
. $GRID_FUNCTIONS

NORDUGRID_CONFIG=${NORDUGRID_CONFIG:-/etc/nordugrid.conf}

if ! test -r "$NORDUGRID_CONFIG"; then
  echo "Can not read $NORDUGRID_CONFIG"
  exit 1
fi

if test "x$1" = "x"; then
  conf_init
  conf_open $NORDUGRID_CONFIG
else
  conf_tmpdir=$1
fi

if conf_match gridftp-server; then
  echo "" 1>&2
  echo "The gridftp-server configuration entry is now obsolete." 1>&2
  echo "Please replace with gridftpd in $NORDUGRID_CONFIG"      1>&2
  exit 1
fi

server=gridftpd

# Defaults

user=""
debug=""

# Read the common section
conf_read common

# Server defaults
logfile="/var/log/$server.log"
port=""
pluginpath="$NORDUGRID_LOCATION/lib"
encryption="no"
allowunknown=""

# Read the main server entry
conf_read $server

if [ `id -u` = 0 ] ; then
  pidfile="/var/run/$server.pid"
else
  pidfile="$HOME/$server.pid"
fi

cat <<-EOF
	# This file was automatically generated by nordugrid startup script. Do not modify.

	EOF

test "x$user"         = "x" || echo "user $user"
test "x$pidfile"      = "x" || echo "pidfile $pidfile"
test "x$logfile"      = "x" || echo "logfile $logfile"
test "x$debug"        = "x" || echo "debug $debug"

test "x$port"         = "x" || echo "port $port"
test "x$pluginpath"   = "x" || echo "pluginpath $pluginpath"
test "x$encryption"   = "x" || echo "encryption $encryption"
test "x$allowunknown" = "x" || echo "allowunknown $allowunknown"

for i in `conf_entries $server`; do
(
	path="/$i"
	plugin=""
	mount=""
	dir=""
        allownew="" 
        configfile=""
	conf_read $server/$i
	if [ -n "$path" -a -n "$plugin" ]; then
	    echo
	    echo "# '`basename $i`' plugin"
	    echo "plugin $path $plugin"
	    if test -n "$mount"; then
		if test "$plugin" = "gaclplugin.so"; then
		    echo "$mount"
		    echo "<gacl>"					    	   
		    echo "<entry>"					    	   
		    echo "<person>"					    	   
		    printf "<dn>%s</dn>\n" "\$subject"
		    echo "</person>"					    	   
		    echo "<allow><read/><write/><list/><admin/></allow>"
		    echo "</entry>"					    	   
		    echo "</gacl>"	     				    	   
		else
		    echo "  mount $mount"
		fi
	    fi

            if test "$plugin" = "jobplugin.so"; then
                test "x$allownew"   = "x" || echo "  allownew $allownew"
                test "x$configfile" = "x" || echo "  configfile $configfile"
	    fi
	    
	    i=0
	    tempvar=$dir
	    while [ ! -z "$tempvar" ]; do
		echo "  dir $tempvar"
		i=$[$i+1]
		tempvar=`eval echo '$dir'_$i`
	    done
	    echo "end"
	fi                
)
done

# Only close if we opened the config file
if test "x$1" = "x"; then
  conf_close
fi
