#!/bin/echo Try "mkroot/mkroot.sh dropbear"

# Example overlay file, adding dropbear (which requires zlib)

echo === download source

download f535367b1a11e2f9ac3bec723fb007fbc0d189e5 \
  https://www.zlib.net/fossils/zlib-1.3.1.tar.gz

download 216ae176572dc008e128042eae82b6aacfdc8a51 \
  https://matt.ucc.asn.au/dropbear/releases/dropbear-2024.86.tar.bz2

echo === Native build static zlib

setupfor zlib
# They keep checking in broken generated files.
rm -f Makefile zconf.h &&
CC=${CROSS_COMPILE}cc LD=${CROSS_COMPILE}ld AS=${CROSS_COMPILE}as ./configure &&
make -j $(nproc) || exit 1

# do _not_ cleanup zlib, we need the files we just built for dropbear

echo === $HOST Native build static dropbear

setupfor dropbear
# Repeat after me: "autoconf is useless"
echo 'echo "$@"' > config.sub &&
ZLIB="$(echo ../zlib*)" &&
CC="$CROSS_COMPILE"cc CFLAGS="-I $ZLIB -O2" LDFLAGS="-L $ZLIB" ./configure --enable-static \
  --disable-wtmp --host="$(basename "$CROSS_COMPILE" | sed 's/-$//')" &&
sed -i 's@/usr/bin/dbclient@ssh@;s@\(#define NON_INETD_MODE\) 1@\1 0@' \
  src/default_options.h &&
make -j $(nproc) PROGRAMS="dropbear dbclient dropbearkey dropbearconvert scp" MULTI=1 SCPPROGRESS=1 &&
${CROSS_COMPILE}strip dropbearmulti &&
mkdir -p "$ROOT"/{bin,etc/{rc,dropbear},var/log} &&
touch "$ROOT"/var/log/lastlog &&
cp dropbearmulti "$ROOT"/bin || exit 1
for i in "$ROOT"/bin/{ssh,dropbear,scp,dropbearkey}
do
  ln -s dropbearmulti $i || exit 1
done
# We didn't cleanup zlib
unset ZLIB
rm -rf ../zlib-*
# cleanup dropbear
cleanup

# user root password root, user guest no password
echo -e 'root:$1$939UTPzb$/PfVYAsF2Hqi/AQ3UBjbK/:::::::\nguest::::::::' > "$ROOT"/etc/shadow &&
chmod 600 "$ROOT"/etc/shadow &&

echo 'netcat -p 22 -L dropbear -iRB &' > "$ROOT"/etc/rc/dropbear &&

# file to run on host to ssh into guest
echo 'ssh -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking=no" ${1:+$1@}127.0.0.1 -p 2222' > "$OUTPUT"/ssh2dropbear.sh &&
chmod +x "$OUTPUT"/ssh2dropbear.sh

# Forward 127.0.0.1:2222 into qemu instance
QEMU_MORE+=" -nic user,hostfwd=tcp:127.0.0.1:2222-:22"
