#!/bin/sh

set -e

PREREQ="cryptroot"

prereqs()
{
	echo "$PREREQ"
}

case $1 in
	prereqs)
		prereqs
		exit 0
		;;
esac

. /usr/share/initramfs-tools/hook-functions

# Additional function for copying plugin (library) from multiarch directory.
# Based on copy_exec.
copy_plugin() {
	local src target x

	src="${1}"
	if [ ${src} = "${src#/}" ]; then
		for x in /${ARCHDIR} /lib /usr/${ARCHDIR} /usr/lib; do
			if [ -e $x/$src ]; then
				src=$(echo $x/$src)
				break
			fi
		done
	fi
	target="${2:-$src}"

	copy_exec "${src}" "${target}" || return $(($? - 1))
}

# Determine multiarch directory
ARCHDIR=$(ldd $SHELL | grep libc\.so |\
          sed -e "s|^.*=> \(.*\)/[^/]*$|\1|" -e "s|^/usr||" -e "s|^/||")
if [ -z "$ARCHDIR" ] && [ -n "$HOSTTYPE" ] && [ -n "$OSTYPE" ]; then
  ARCHDIR=$HOSTTYPE-$OSTYPE
fi
if [ -z "$ARCHDIR" ]; then
  ARCHDIR=$(uname -i)
  if [ "$ARCHDIR" = "unknown" ]; then
    ARCHDIR=$(uname -m)
  fi
  if [ "$ARCHDIR" = "ppc64le" ]; then
    ARCHDIR="powerpc64"
  fi
  if [ "$ARCHDIR" = "ppc64el" ]; then
    ARCHDIR="powerpc64"
  fi
  ARCHDIR="*${ARCHDIR}*"
fi

# Hooks for loading smartcard reading software into the initramfs

# Install directories needed by smartcard reading daemon, command, and
# key-script
for dir in etc/opensc lib usr/lib var/run tmp ; do
	if [ ! -d ${DESTDIR}/${dir} ] ;
	then
		mkdir -p ${DESTDIR}/${dir}
	fi
done

# Install pcscd daemon, drivers, conf file
copy_exec /usr/sbin/pcscd /sbin

copy_plugin libpcsclite.so.1

find /usr/lib/pcsc ! -type d |
while read PSCS_FILE; do
  if [ ! -x ${PSCS_FILE} ] && [ ${PSCS_FILE} = ${PSCS_FILE%.so} ]; then
    [ -d ${DESTDIR}${PSCS_FILE%/*} ] || \
    mkdir -p ${DESTDIR}${PSCS_FILE%/*}
    cp -pL $PSCS_FILE ${DESTDIR}${PSCS_FILE%/*}
  else
    copy_exec $PSCS_FILE
  fi
done

if [ -d /etc/reader.conf.d ]; then
    cp -pLR /etc/reader.conf.d ${DESTDIR}/etc/
fi
if [ -e /etc/reader.conf ]; then
    cp -pL /etc/reader.conf ${DESTDIR}/etc/
fi

# Install opensc commands and conf file
copy_exec /usr/bin/opensc-tool /bin/
copy_exec /usr/bin/pkcs15-crypt /bin/
copy_exec /usr/bin/pkcs15-tool /bin/
cp -pL /etc/opensc/opensc.conf ${DESTDIR}/etc/opensc/

# Install opensc interface library
copy_plugin opensc-pkcs11.so

# Install other required utilities
copy_exec /bin/grep /bin
copy_exec /bin/mv /bin
copy_exec /bin/cat /bin
copy_exec /bin/sleep /bin
copy_exec /usr/bin/opensc-explorer /bin
copy_exec /usr/bin/openssl /bin
copy_exec /usr/bin/perl /bin
copy_exec /bin/rm /bin
copy_exec /usr/bin/xxd /bin
copy_exec /usr/bin/killall /bin
copy_exec /bin/sed /bin
copy_exec /usr/bin/tr /bin
copy_exec /bin/bash /bin

# Main scripts
copy_exec /usr/bin/cryptosmartcard.sh /bin
copy_exec /usr/bin/cardpincheck /bin

# Libraries
copy_plugin libncursesw.so.[0-9]

# LUKS keys
if [ -e /etc/trinity/luks/card ]
then
	cp -LRp /etc/trinity/luks/card ${DESTDIR}/tde_luks_keys
else
	mkdir -p ${DESTDIR}/tde_luks_keys
fi

exit 0
