#!/bin/sh
# 4137717, 4319347

# must be run chrooted to the target disk
DEVMOUNT_CALLED=0
SECURITYD_LAUNCHED=0

if [ "$3" != "/" ]; then
	/sbin/mount_devfs devfs /dev
	DEVMOUNT_CALLED=1
fi

if [ `/bin/ps auxww |/usr/bin/grep securityd |/usr/bin/grep -v grep | wc -l` == 0 ]; then 
	/usr/sbin/securityd -X
	SECURITYD_LAUNCHED=1
fi	

if [ ! -f /Library/Keychains/System.keychain ]; then
  if [ ! -d /Library/Keychains ]; then
        /bin/mkdir -p /Library/Keychains
        /usr/sbin/chown root:admin /Library/Keychains
        /bin/chmod 755 /Library/Keychains
  fi
  sleep 2       # give SecurityServer a chance to come up
  /usr/sbin/systemkeychain -C
fi

if [ ! -f "/System/Library/Keychains/X509Anchors" ]; then
        "/usr/bin/security" create-keychain -p X509Anchors "/System/Library/Keychains/X509Anchors"
fi

if [ ! -f "/System/Library/Keychains/X509Certificates" ]; then
        "/usr/bin/security" create-keychain -p X509Certificates "/System/Library/Keychains/X509Certificates"
fi

if [ -d "/System/Library/Keychains/Anchors" ]; then
        cd "/System/Library/Keychains/Anchors/"
        "/usr/bin/security" add-certificate -k "/System/Library/Keychains/X509Anchors" *

        /bin/rm -rf "/System/Library/Keychains/Anchors"
fi

if [ -d "/System/Library/Keychains/Certificates" ]; then
        cd "/System/Library/Keychains/Certificates/"
        "/usr/bin/security" add-certificate -k "/System/Library/Keychains/X509Certificates" *

        /bin/rm -rf "/System/Library/Keychains/Certificates"
fi

if [ $SECURITYD_LAUNCHED -eq 1 ]; then
	for SECURITY_PID in `/bin/ps auxww |/usr/bin/grep securityd |/usr/bin/grep -v grep|/usr/bin/awk '{print $2;}'`
	do
		/bin/kill $SECURITY_PID >/dev/null 2>&1
	done
fi

if [ $DEVMOUNT_CALLED -eq 1 ]; then
	/sbin/umount /dev
fi

