#!/bin/sh
# Copyright 1998 Sun Microsystems, Inc. All Rights Reserved

SCRIPT_NAME=`basename $0`
SCRIPT_DIR=`dirname $0`

# If SCRIPT_DIR is not an absolute path name
# (i.e. it doesn't begin with a '/')
# then we try to find the absolute path name using 'pwd'.

case $SCRIPT_DIR in
/* )
	;;
 * )
	INVOKING_DIRECTORY=`/usr/bin/pwd`
	SCRIPT_DIR=$INVOKING_DIRECTORY/$SCRIPT_DIR
	;;
esac

BASEDIR=$SCRIPT_DIR/../../..

certonly="false"

myExit()
{
        gettext SUNWhttp "\nExiting SSL setup  .. \n"
        exit 1
}
 
usage()
{
  gettext SUNWhttp "usage: install_certs [-c] <-p path> [-i ip] [uid]\n"
  gettext SUNWhttp "where..\n"
  gettext SUNWhttp "[-c]\t\toption to indicate re-installation of a local certificate\n"
  gettext SUNWhttp "<-p path>\tcertificates directory.\n"
  gettext SUNWhttp "[-i ip]\t\tIP address of the host the certificate is for.\n"
  gettext SUNWhttp "[uid]\t\tthe user id of web server process. (default uid = 0)\n\n"
}
 
installLocal()
{
  /usr/bin/skicert -Rhes	# remove all existing certs from before, if any

  if [ "$certonly" = "true" ]; then
    /usr/bin/skistore -c "$filedir/certs/$IP.CERT"
  else
    /usr/bin/skistore -d $filedir
  fi    
  
  if [ $? = 1 ]; then
    myExit
  fi
 
  # We have to skilogin the key under uid 0 (in addition to $uid),
  # because in the case where we request an external certificate,
  # we run the script that generates the certification request
  # as root (uid 0)!
  if [ -z "$IP" ]; then
  	/usr/bin/skilogin -h 0 $uid
  else
	/usr/bin/skilogin -h -L $IP 0 $uid
  fi

  if [ $? = 1 ]; then
    myExit
  fi
}
 
 
# ----------------Main Routine--------------------------------------
 
WHO=`id | sed "s/uid=[0-9]*(\([^ )]*\)).*/\1/"`
 
if [ $WHO != "root" ]; then
       gettext SUNWhttp "ERROR: You must be \"root\" to run this script.\n"
       myExit
fi
 
while getopts "p:i:c" arg
do
  case $arg in
    c)      certonly="true";;
    p)	    filedir=$OPTARG;;
    i)      IP=$OPTARG;;
    \?)     usage
            myExit;;
  esac
done
 
shift `expr $OPTIND - 1`
uid=`expr "$1"`

if [ -z "$filedir" ]; then
  usage
  myExit
fi

if [  ! -d "$filedir" ]; then
  gettext SUNWhttp "$filedir directory does not exist.\n"
  myExit
fi

if [ -z "$uid" ]; then
  uid=0
fi

if [ -z "$IP" ] && [ "$certonly" = "true" ]; then
      gettext SUNWhttp "ERROR: You must enter an IP address.\n"
      usage
      myExit
fi

installLocal

