#!/bin/sh
# Copyright 1998 Sun Microsystems, Inc. All Rights Reserved
#
# Send a certificate request to an external Authority
#
filedir="/tmp"
SERVER_VERSION="SWS-1.0"
clean="true"

usage()
{
  gettext SUNWhttp "usage: \n"
  gettext SUNWhttp "send_request [-o <output filepath>] <ip>\n"
  gettext SUNWhttp "where....\n"
  gettext SUNWhttp "<ip>\t\t\taddress of the host the certificate is for.\n"
  gettext SUNWhttp "[-o output filepath]\tSpecify path name for storing\n"
  gettext SUNWhttp "\t\t\tcertificate request output file.\n"
  gettext SUNWhttp "If you don't specify one, no file will be saved.\n\n"
}

getAttributes() {


hostdn=`(/usr/bin/fnattr host/$hname onc_distinguished_name | /usr/bin/grep Value) 2>/dev/null | /usr/bin/cut -d: -f2`

line=`echo "$hostdn" | /usr/bin/cut -d"," -f1`
count=2

while [ "$line" ]
do
  line=`echo $line`
  old_line=$line
  
  case "$line" in

	 CN=* | cn=*)    cn=`echo $line | sed 's/.*=//'`;;
	 OU=* | ou=*)    ou=`echo $line | sed 's/.*=//'`;;
	 O=*  | o=*)     o=`echo $line | sed 's/.*=//'`;;
	 L=*  | l=*)     l=`echo $line | sed 's/.*=//'`;;
 	 ST=* | st=*)    st=`echo $line | sed 's/.*=//'`;;
 	 C=*  | c=*)     c=`echo $line | sed 's/.*=//'`;;
	 *) 		 gettext SUNWhttp "Unrecognized Distinguished Name\n";;
  esac

  line=`echo "$hostdn" | /usr/bin/cut -d"," -f"$count"`

  if [ "$old_line" = "$line" ]; then
    break
  fi
  
  count=`expr $count + 1`
  
done
}

#-------------main routines-----------------------------------
WHO=`id | sed "s/uid=[0-9]*(\([^ )]*\)).*/\1/"`

if [ $WHO != "root" ]; then
       gettext SUNWhttp "ERROR: You must be \"root\" to run this script.\n"
       exit
fi


while getopts o: arg
do
  case $arg in
    o)      filedir="$OPTARG"; clean="false";;
    \?)     usage
            exit 1;;
  esac
done

shift `expr $OPTIND - 1`
IP="$1"

if [ -z "$IP" ]; then
  usage
  exit 1
fi

hname=`getent hosts $IP | awk '{print $2}'`

if [ ! -d "$filedir" ] && [ "$clean" = "false" ]; then
  gettext SUNWhttp "$filedir is not a directory\n"
  exit
fi

# getAttributes

end="n"

# default UID of root for sending request

/usr/bin/skilogin -h -L $IP 0
/usr/bin/certreq -h -L $IP -b > $filedir/cert.request

if [ $? = 1 ]; then
  exit 1
fi

if [ ! "$to" ]; then
  gettext SUNWhttp "A certificate request file is generated and stored in : $filedir/cert.request\n"
  exit
fi

