#!/bin/ksh
#
# ident "%W% %E% SMI"
#
# Copyright 1996-2002 Sun Microsystems, Inc.  All rights reserved.
#
# create key packages and certificates for http server
#

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/..

# setup default values
validity="3*365"
keysize="512"

myExit() {
        echo ""
        gettext SUNWutws "Exiting setup  .. \n"
        exit 1
}


usage()
{
  gettext SUNWhttp "usage: \n"
  gettext SUNWhttp "utsslgencrd [-f input file] [-r rootca] <-d output directory> <-i ip>\n"
  gettext SUNWhttp "where....\n\n"
  gettext SUNWhttp "[-r rootca]\t\tRootCA user name on this system\n\n"
  gettext SUNWhttp "[-f input file]\t\tSpecify full path name for the file containing\n"
  gettext SUNWhttp "\t\t\ta list of Trusted Root CA certificates.\n\n" 
  gettext SUNWhttp "<output directory>\tPath where the output will be stored.\n"
  gettext SUNWhttp "\t\t\tThese files are needed to later store\n"
  gettext SUNWhttp "\t\t\tthe generated credentials(keypkgs and\n"
  gettext SUNWhttp "\t\t\tcertificates) into the naming service.\n\n"
  gettext SUNWhttp "<ip>\t\t\tThe ip address from where you will run\n"
  gettext SUNWhttp "\t\t\tyour http server.\n"
}


query_user()
{
  end="n"

  gettext SUNWhttp "Creating Public/Private key pairs and certificates\n"
  gettext SUNWhttp "for your webserver...\n"

  while [ "$end" != "y" ]
  do
      gettext SUNWhttp "Enter Host Name on which you run httpd server:\n"
      gettext SUNWhttp "(Hit return to use $host_name)\n"
      read i_host_name

      gettext SUNWhttp "Enter Domain Name for your server:(e.g. eng.sun.com)\n"
      read domain
      if [ "$domain" ]; then
	end="y"
      else
	echo " "
	gettext SUNWhttp "Invalid domain name.  Try again...\n"
      fi
  done

  if [ "$i_host_name" ]; then
    host_name=$i_host_name
  fi
  
  echo "$ip ${host_name}" > "$outputdir/host_list"

  gettext SUNWhttp "Enter Distinguished Name Suffix for your server (eg: \"o=SUN, c=US\") :\n"
    read dnsuffix
    
    # check DN suffix: No CN field should have been specified.

    newdn=`echo $dnsuffix | sed 's/cn=/**/'`
    newdn1=`echo $dnsuffix | sed 's/cn =/**/'`
    newdn2=`echo $dnsuffix | sed 's/CN=/**/'`
    newdn3=`echo $dnsuffix | sed 's/CN =/**/'`
    if [[ "$dnsuffix" != "$newdn" || "$dnsuffix" != "$newdn1" || "$dnsuffix" != "$newdn2" || "$dnsuffix" != "$newdn3" ]]; then
      gettext SUNWhttp "ERROR: The DN suffix must not contain the common name (CN) field.\n"
      myExit
    fi

  gettext SUNWhttp "Please Provide the password to encrypt your server's private key.\n"
  gettext SUNWhttp "You will need it when you install the certificates.\n"
  trap "stty echo" INT
  password=`$BASEDIR/lib/sslpasswd`

  if [ ! "$password" ]; then
    gettext SUNWhttp "Error: Unable to retrieve password.\n"
    myExit
  fi
}


getKeysize()
{
  # This routine used to determine if global or domestic sectools
  # were installed and set keysize based upon that.
  # The domestic version can support 768 or 1024 as keysize,
  # BUT clients (global clients, or any client for a 40-bit accessible site)
  # baulk if the keysize is too big for them.

  keysize=512
}

prepareFile()
{
  echo "SKI_ENTITIES_TYPE:host"
  if [ "$dnsuffix" ]; then
    echo "SKI_DN_SUFFIX:$dnsuffix"
  fi
  echo "SKI_HOST_DOMAIN:$domain"
  echo "SKI_VALIDITY:$validity"
  echo "SKI_KEYSIZE:$keysize"
  echo "SKI_PASSWORD:$password"
  echo "SKI_ENTITIES_FILE:$outputdir/host_list"
  echo "SKI_CRED_DIR:$outputdir"
  echo "SKI_ROOT_CA_DN:$rootdn"
  echo "SKI_ROOT_CA_LOGIN:$rootca"
  if [ "$inputfile" ]; then
      echo "SKI_TRUSTED_KEYS:$inputfile"
  fi
}


archiveFiles()
{
  if [ -f "/etc/opt/SUNWut/http/ski/ski_passwords" ]; then
    /usr/bin/mv "/etc/opt/SUNWut/http/ski/ski_passwords" "/etc/opt/SUNWut/http/ski/ski_passwords.old"
  fi

  if [ -f "$outputdir/ski_passwords" ]; then
    /usr/bin/mv "$outputdir/ski_passwords" "$outputdir/ski_passwords.old"
  fi

  if [ -f "$outputdir/new_cred_list" ]; then
    /usr/bin/mv "$outputdir/new_cred_list" "$outputdir/new_cred_list.old"
  fi
  
  if [ -d "$outputdir/keypkgs" ]; then
    /usr/bin/mv "$outputdir/keypkgs" "$outputdir/keypkgs.old"
  fi

  if [ -d "$outputdir/certs" ]; then
    /usr/bin/mv "$outputdir/certs" "$outputdir/certs.old"
  fi

}

#-----------------Main Routines------------------------------

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

if [ $WHO = "root" ]; then
  gettext SUNWhttp "ERROR: You must NOT run this script as root.\n"
  gettext SUNWhttp "Please run this as the Root CA user that was setup before running utcrca.\n"
  gettext SUNWhttp "Please run utcrca before running this script.\n"
  myExit
fi  

while getopts "f:r:i:d:" arg
do
  case $arg in
    f)      inputfile="$OPTARG";;
    r)      rootca="$OPTARG";;
    d)      outputdir="$OPTARG";;
    i)      ip="$OPTARG";;
    \?)     usage
	    exit 1;;
  esac
done

if [ -z "$rootca" ]; then
  gettext SUNWhttp "Enter the username of the RootCA user on this system: \n"
  read rootca
fi

# check for '_' in rootca user name
rca=`echo $rootca | sed 's/\(.*\)_\(.*\)/\1__\2/'`

if [ ! -s "/var/fn/fns_user_$rca.ctx.dir" ] &&
  [ ! -s "/var/fn/fns_user_$rca.ctx.pag" ]; then
    gettext SUNWhttp "Local Root CA not found on this machine. Run utcrca first!\n"
    myExit
fi

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

if [ ! "$ip" ]; then
  gettext SUNWhttp "ERROR: You must specify an IP address.\n"
  usage
  myExit
fi

# check for correct format of IP address
newip=`echo $ip | sed 's/[^0-9.].*/NOT/'`
if [ $ip != $newip ]; then
  gettext SUNWhttp "ERROR: IP address is incorrectly formatted.\n"
  myExit
fi  

if [ $inputfile ]; then
  if [ ! -f $inputfile ]; then
    gettext SUNWhttp "$inputfile does not exist or is not accessible.\n"
    myExit
  fi
fi

if [ ! "$outputdir" ]; then
  gettext SUNWhttp "ERROR: Please specify a directory to store credentials.\n"
  myExit
fi

if [ ! -d $outputdir ]; then
  gettext SUNWhttp "$outputdir is not a directory!\n"
  myExit
fi

rootdn=`/opt/SUNWut/http/ski/bin/skicert -G -k $rootca | /usr/bin/grep Subject: | /usr/bin/cut -d: -f2`

hostname_guess=`/usr/bin/getent hosts $ip | awk '{print $2}'`
if [ -n "$hostname_guess" ]; then
  host_name=$hostname_guess
else
  host_name=`/usr/bin/hostname`
fi

query_user
getKeysize
prepareFile > "$outputdir/host_config"
archiveFiles

## If not generating local certs: use -k option

#if [ "$cert" != "n" ]; then
  credsopt="-c"
#else
#  credsopt="-k -c"
#fi  
  
/opt/SUNWut/http/ski/bin/ccreds $credsopt $outputdir/host_config
if [ $? = 1 ]; then
  exit
fi

/usr/bin/mv /etc/opt/SUNWut/http/ski/ski_passwords $outputdir/ski_passwords
