#!/bin/sh
# Nico Schottelius, 2019-12-09
# the ugly code is llnu

#this can only run in the ungleich-tools directory because of the cat magiccommand........

if [ $# -ne 2 ]; then
    echo $0 suite out-directory
    echo out-directory: into which directory to place resulting files
    echo suite is for instance ascii, beowulf, etc
    exit 1
fi

suite=$1; shift
outdir=$1; shift

date=$(date +%F)

basename=${suite}-${date}
dir=${outdir}/${basename}
kernel=${outdir}/kernel-${basename}
initramfs=${outdir}/initramfs-${basename}
keyurl=https://code.ungleich.ch/ungleich-public/__ungleich_staff_ssh_access/raw/master/files

debootstrap "${suite}" "${dir}"

# need non-free for firmware-bnx2
echo "deb http://pkgmaster.devuan.org/merged ${suite} main contrib non-free" > ${dir}/etc/apt/sources.list

chroot ${dir} apt update
chroot ${dir} apt install  -y openssh-server rdnssd linux-image-amd64 firmware-bnx2


cp ${dir}/boot/vmlinuz-* ${kernel}

echo '* * * * * root ip -o -6 addr show | grep -E -v " lo |one" > /etc/issue'  > ${dir}/etc/cron.d/ipv6addr

mkdir -p ${dir}/root/.ssh

for key in balazs dominique jinguk nico; do
    curl -s ${keyurl}/${key}.pub >> ${dir}/root/.ssh/authorized_keys
done

################################################################################
# networking

# always lo
cat > ${dir}/etc/network/interfaces << EOF
auto lo
iface lo inet loopback

source-directory /etc/network/interfaces.d
EOF

# find the boot interfaces at boot
cat > ${dir}/etc/rc.local <<EOF
mac=\$(cat /proc/cmdline | tr ' ' '\n' | awk -F= '/bootdev/ { print \$2 }')
dev=\$(ip -o link | awk -F: "/\$mac/ { print \\\$2 }" | sed 's/ *//g')

cat > /etc/network/interfaces.d/bootinterface << eof
auto \$dev
iface \$dev inet6 auto
eof

ifup "\${dev}"

exit 0
EOF

chmod a+rx ${dir}/etc/rc.local"

# ensure there is /init in the initramfs -> otherwise there is a kernel panic
# reason: initramfs is designed to be PRE regular os, so /init usually hands over to /sbin/init
# in our case, they are just the same
ln -s /sbin/init ${dir}/init

# Finally building the initramfs
( cd ${dir} ; find . | cpio -H newc -o | gzip -9 > ${initramfs} )