#!/bin/sh
cd $(dirname $0)

export PATH=/opt/nec/eds/bin:$PATH
export LD_LIBRARY_PATH=/opt/nec/eds/lib:$LD_LIBRARY_PATH
export PERCIOROOT=/opt/nec/eds
export PERCIOENVPATH=/opt/nec/eds/env

EDS_BINPATH=/opt/nec/eds/bin

OLD_CERTID=eidmInternalUser
NEW_CERTID=eidmInternalUser
NEW_CERTFILE=./eidmInternalUser2.der
TYPE=eidm

if test $# -ne 3
then
    echo "Usage: $0 port binddn password"
    exit 1
fi

procnum=`/bin/ps -ef | /bin/grep edldapd | /bin/grep -v grep | /usr/bin/wc -l`
if test $procnum -eq 0
then
  echo "Please start EDS."
  exit 2
fi

portno=$1
binddn=$2
password=$3

$EDS_BINPATH/EDCERT -print -keyid $OLD_CERTID >/dev/null 2>&1
if test $? -ne 0
then
  echo "keyid $OLD_CERTID is not exist."
  echo "exit import process."
  exit 3
fi

echo "To import $NEW_CERTID certficate, EDS Server will be stopeed."
echo "Do you want to continue?"
while :
do
  echo -e "yes/no (default: no): \c"
  read YN
  null=${YN:="NO"}
  YESNO=`echo $YN | tr "[a-z]" "[A-Z]"`
  if [ $YESNO = "YES" ]
  then
    break
  else
    echo "Import process is canceled."
    exit 0
  fi
done

$EDS_BINPATH/edconfig -h localhost -p $portno -D "$binddn" -w "$password" -view ldapCertificateKeyID >/dev/null 2>&1
if test $? -ne 0
then
  echo "view ldapCertificateKeyID failed."
  exit 5
fi

certid=`$EDS_BINPATH/edconfig -h localhost -p $portno -D "$binddn" -w "$password" -view ldapCertificateKeyID 2>&1 | /usr/bin/awk '{print $2}'`
if test $certid = $OLD_CERTID
then
  $EDS_BINPATH/edconfig -h localhost -p $portno -D "$binddn" -w "$password" -replace ldapCertificateKeyID:$NEW_CERTID
  if test $? -ne 0
  then
    echo "replace ldapCertificateKeyID failed."
    echo "exit import process."
    exit 6
  fi
fi

echo "Stopping EDS Server..."
$EDS_BINPATH/EDAGENT stop

$EDS_BINPATH/EDCERT -remove -keyid $OLD_CERTID -nocheck >/dev/null 2>&1
if test $? -ne 0
then
  echo "remove $OLD_CERTID failed."
  echo "exit import process."
  exit 10
fi

./import_builtincert -cert $NEW_CERTFILE -type $TYPE -keyid $NEW_CERTID

if test $? -ne 0
then
    echo "import $NEW_CERTFILE failed."
    exit 7
fi

$EDS_BINPATH/EDCACERT -list | /bin/grep "EDS built-in CA2"
if test $? -ne 0
then
  $EDS_BINPATH/EDCACERT -import -in ./cacert.der -trust -nocheck
  if test $? -ne 0
  then
    echo "import CA cert failed."
    exit 8
  fi
fi

echo "Starting EDS Server..."
$EDS_BINPATH/EDAGENT start
if test $? -ne 0
then
  echo "start EDS failed."
  exit 9
fi

echo "success."
exit 0


