#!/bin/sh
#	Copyright (c) 1997 Dynamic Software AB,	All Rights Reserved
#
#	Dynamic Software AB, DynaSoft
#
#
# Read a certificate file into database with orrect type and
# removes it if successful. This is not a generic import tool,
# it is used by boks_bru when restoring an old (4.3) database.
# It makes assumptions about file names based on this.
#
# Now also do host kpg's. Look at extension to filename
# to determine type:
# .crt -> certificate
# .kpg -> key package
#


# Determine type of CERT and insert ino DB
#
insert_cert () {
    file="$1"
    type=

    if expr "$file" : '.*T=PIN\.crt$' > /dev/null 2>&1; then
	type=PIN
    elif expr "$file" : '.*T=PCPROT\.crt$' > /dev/null 2>&1; then
	type=PCPROT
    elif expr "$file" : '.*T=CA\.crt$' > /dev/null 2>&1; then
	type=CA
    elif expr "$file" : '.*T=USER\.crt$' > /dev/null 2>&1; then
	type=USER
    elif expr "$file" : '.*T=ADMIN\.crt$' > /dev/null 2>&1; then
	type=ADMIN
    elif expr "$file" : '.*T=HOST\.crt$' > /dev/null 2>&1; then
	type=HOST
    fi

    if [ x"$type" = x ]; then
	# does not conform to old name conventions
	return
    fi

    user=`basename "$file" .crt`

    if [ $type = "HOST" ]; then
	user=`expr "$user" : '.*;SN=\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)'`
    fi

    if dscertadm -I -m FILE -T $type -i "$file" -m BOKS -o "$user" > /dev/null 2>&1; then
	rm -f "$file"
    fi
}


# Check that file is a host kpg, and if so insert into DB
#
insert_hostkpg () {
    file="$1"

    ipkpgmatch='.*/[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*.kpg$'

    if expr "$file" : "$ipkpgmatch" > /dev/null 2>&1; then
	ip=`basename "$file" .kpg`
	if keypkgadm -I -m FILE -e "$file" -m BOKS -o "$ip" -T HOST > /dev/null 2>&1; then
	    rm -f "$file"
	fi
    fi
}


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

if [ ! -f "$1" ]; then
    exit
fi

certmatch='.*\.crt$'

if expr "$1" : '.*\.kpg$' > /dev/null 2>&1; then
    insert_hostkpg "$1"
elif expr "$1" : '.*\.crt$' > /dev/null 2>&1; then
    insert_cert "$1"
fi

