#!/bin/bash

# Adjusted for slackware's initrd
# Andrew Clemons
# August 2016

PREREQ=""
prereqs()
{
	echo "$PREREQ"
}

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

if [ -z "$DESTDIR" ] ; then
	echo "Missing destination directory. Use DESTDIR= to pass the destination directory."
	exit 1
fi

# create the needed directories
for i in /etc/dropbear /etc/early-ssh /root /root/.ssh /sbin /bin /usr/bin /var /var/log; do
	[ ! -e "${DESTDIR}${i}" ] && mkdir -p "${DESTDIR}${i}"
done

if [ ! -e "${DESTDIR}/tmp" ] ; then
	mkdir "${DESTDIR}/tmp"
	chmod 1777 "${DESTDIR}/tmp"
fi

# copy the needed executables
cp -a /usr/bin/dropbearmulti $DESTDIR/sbin/dropbear
cp -a /usr/share/mkinitrd/scripts/early_ssh $DESTDIR/

# copy the configs
cp -rp /etc/dropbear/dropbear_dss_host_key $DESTDIR/etc/dropbear/
cp -rp /etc/dropbear/dropbear_rsa_host_key $DESTDIR/etc/dropbear/
cp -rp /etc/dropbear/dropbear_ecdsa_host_key $DESTDIR/etc/dropbear/
cp -rp /etc/localtime $DESTDIR/etc/
[ -f /root/.ssh/authorized_keys ] && cp -rp /root/.ssh/authorized_keys $DESTDIR/root/.ssh/authorized_keys
cp -rp /etc/login.defs $DESTDIR/etc/
cp -rp /etc/early-ssh/early-ssh.conf $DESTDIR/etc/early-ssh/

. /etc/early-ssh/early-ssh.conf

if [ "$PASSWD_OVERRIDE" != "" ]; then
	cat $PASSWD_OVERRIDE >> $DESTDIR/etc/passwd
fi

if [ "$SHADOW_OVERRIDE" != "" ]; then
	cat $SHADOW_OVERRIDE >> $DESTDIR/etc/shadow
fi

if [ "$GROUP_OVERRIDE" != "" ]; then
	cat $GROUP_OVERRIDE >> $DESTDIR/etc/group
fi

sed -i 's#/bin/bash#/bin/sh#g' $DESTDIR/etc/passwd
