#! /bin/sh
#
#
INSTALL=install
PREFIX=/etc/grid-security/certificates
MKDIR=mkdir
SED=sed
PROFILE=ANY
PROFILES=""

while :
do
  case "$1" in
  --prefix=* ) 
	PREFIX=`echo $1 | sed -e 's/--prefix=//'`
	shift 
	;;
  --with-mkdir=* ) 
	MKDIR=`echo $1 | sed -e 's/--with-mkdir=//'`
	shift 
	;;
  --with-install=* ) 
	INSTALL=`echo $1 | sed -e 's/--with-install=//'`
	shift 
	;;
  --with-profile=* ) 
	PROFILE=`echo $1 | sed -e 's/--with-profile=//'`
        PROFILES="$PROFILE $PROFILES"
	shift 
	;;
  -- ) shift ; break ;;
  -* ) echo "Unknown argument to $0" ; exit 1 ;;
  * ) break ;;
  esac
done

case "$#" in
0 )	;;
* )	cat <<EOF
Usage: $0
    [--prefix=path]          Installation path
                             default: /etc/grid-security/certificates
    [--with-mkdir=path]      name of mkdir program supporting -p
                             default: mkdir
    [--with-install=path]    name of the BSD install programme
                             default: install
    [--with-profile=profile] selected CA accreditation profile
                             default: ANY
EOF
	exit 0
;;
esac

[ x"$PROFILES" = x"" ] && PROFILES=ANY

# collect the CAs per profile
exec 3<&0
exec 0<accredited.in
while read ca pr r ; do eval p$pr=\"\$p$pr $ca\" ; eval l=\"\$l $ca\" ; done 
exec 0<&3

# create the makefile

cat > Makefile <<EOFA
# generated automatically by configure
# $@
#
prefix=$PREFIX
install=$INSTALL
mkdir=$MKDIR
profile=$PROFILE

all: compile

compile:;
	@echo "Ready to install in \$(prefix)."

\$(prefix):
	\$(mkdir) -p \$(prefix)

prep: \$(prefix)

EOFA

for ca in $l
do
  hash=`basename $ca/*.0 .0`
  echo -ne "install-$ca: prep\n" >> Makefile
  echo -ne "\t\$(install) $ca/$hash.0 \$(prefix)/\n" >> Makefile
  echo -ne "\t\$(install) $ca/$hash.signing_policy \$(prefix)/\n" >> Makefile
  [ -f $ca/$hash.crl_url ] &&
    echo -ne "\t\$(install) $ca/$hash.crl_url \$(prefix)/\n" >> Makefile
  echo -ne "\n" >> Makefile
done

echo -ne "install-ANY: prep" >> Makefile
for ca in $l; do echo -ne " install-$ca" >> Makefile ; done
echo -ne "\n\n" >> Makefile

if [ $PROFILES = ANY ]; then
 echo -ne "install: install-ANY\n\n" >> Makefile
else
 echo -ne "\n# Default: Installing CAs for profile(s) $PROFILES\n" >> Makefile
 echo -ne "install: prep" >> Makefile
 for p in $PROFILES ; do
  eval list=\$p$p
  for i in $list ; do echo -ne " install-$i" >> Makefile ; done
 done
 echo -ne "\n\n" >> Makefile
fi
