#!/bin/sh

# apk add qemu-img qemu-openrc losetup blkid parted e2fsprogs wget tar
set -eu

: "${DISK:=bpi-f3-mmc.img}"
: "${DISKSIZE:=600M}"

readonly SCRIPT="${0##*/}"
readonly TMPDIR="$(mktemp -dt "${SCRIPT%.*}".XXXXXX)"
readonly APK_KEY="alpine-devel@lists.alpinelinux.org-60ac2099.rsa.pub"
readonly MIRROR="https://dl-cdn.alpinelinux.org/alpine"
readonly LOOPDEV="$(losetup --find)"
readonly BOOTDEV="$LOOPDEV"p1
readonly ROOTDEV="$LOOPDEV"p2

cleanup() {
	set +e
	mountpoint -q "$TMPDIR"/boot && umount "$TMPDIR"/boot
	mountpoint -q "$TMPDIR" && umount "$TMPDIR"
	losetup --detach-all
	rm -rf "$TMPDIR"
}

trap cleanup EXIT INT

rm -f $DISK
truncate -s $DISKSIZE $DISK

kernel="linux-bpi-f3-6.6.36-r2.apk"
bootloader="bpi-f3-u-boot-syslinux.tar.xz"

if [ ! -f $bootloader ]; then
  wget https://github.com/pyavitz/binary/releases/download/060420/"$bootloader"
	tar xf $bootloader
fi

if [ ! -f $kernel ]; then
  wget https://dev.alpinelinux.org/~mps/riscv64/"$kernel"
fi

echo "Paritioning disk"
parted -s "$DISK" mktable msdos > /dev/null
parted -s "$DISK" unit s -- mkpart primary ext4 8192 128MiB > /dev/null
parted -s "$DISK" -- mkpart primary ext4 136MiB 100% > /dev/null

echo "Creating dirs and mounting"
losetup -P "$LOOPDEV" "$DISK"
mkfs.ext4 -qL mmc.bfs "$BOOTDEV"
mkfs.ext4 -qL mmc.rfs "$ROOTDEV"
mount -t ext4 "$ROOTDEV" "$TMPDIR"
mkdir -p "$TMPDIR"/boot
mkdir -p "$TMPDIR"/etc/apk/keys
mount -t ext4 "$BOOTDEV" "$TMPDIR"/boot

echo "flashing boot loader"
# we use boot loader made by https://github.com/pyavitz/debian-image-builder/
# tarbal is downloaded from this url:
# https://github.com/pyavitz/binary/releases/download/060420/bpi-f3-u-boot-syslinux.tar.xz
# and untared to bpi-f3-u-boot-syslinux
dd if=bpi-f3-u-boot-syslinux/"bootinfo_emmc.bin" of=${LOOPDEV} bs=512 conv=notrunc
dd if=bpi-f3-u-boot-syslinux/"FSBL.bin" of=${LOOPDEV} bs=512 seek=1 conv=notrunc
dd if=bpi-f3-u-boot-syslinux/"FSBL.bin" of=${LOOPDEV} bs=512 seek=512 conv=notrunc
dd if=bpi-f3-u-boot-syslinux/"fw_dynamic.bin" of=${LOOPDEV} bs=512 seek=1280 conv=notrunc
dd if=bpi-f3-u-boot-syslinux/"u-boot.bin" of=${LOOPDEV} bs=512 seek=2048 conv=notrunc

echo "Setup apk keys and repositories"
wget -qP "$TMPDIR"/etc/apk/keys https://alpinelinux.org/keys/"$APK_KEY"
printf "$MIRROR/edge/%s\n" main community testing > "$TMPDIR"/etc/apk/repositories

echo "installing base packages"
apk --allow-untrusted --root "$TMPDIR" --arch riscv64 --initdb add \
	alpine-base alpine-baselayout alpine-conf kmod openrc \
  dbus util-linux blkid chrony \
	sysfsutils ssl_client ca-certificates-bundle alpine-keys \
	ethtool f2fs-tools e2fsprogs e2fsprogs-extra libudev-zero libudev-zero-helper \
	iwd installkernel linux-firmware-none parted \
	agetty openresolv tar tzdata openssh wget mkinitfs

apk --allow-untrusted --root "$TMPDIR" --arch riscv64 add $kernel

echo "Setting up services"
for rc in boot/bootmisc boot/hostname boot/modules boot/sysctl boot/urandom boot/networking \
	sysinit/devfs sysinit/hwdrivers sysinit/mdev sysinit/modules \
	shutdown/mount-ro shutdown/killprocs \
	default/dbus default/chronyd default/local; do
	ln -s /etc/init.d/"${rc##*/}" "$TMPDIR"/etc/runlevels/"$rc"
done

echo "setting basics for libudev-zero/mdev"
echo 'SUBSYSTEM=drm;.*   root:video 660 */usr/libexec/libudev-zero-helper' >>  $TMPDIR/etc/mdev.conf
echo 'SUBSYSTEM=input;.* root:input 660 */usr/libexec/libudev-zero-helper' >>  $TMPDIR/etc/mdev.conf
echo "LABEL=mmc.bfs	/boot	ext4	auto" >> $TMPDIR/etc/fstab

echo "Settting boot loader"
bootuuid=$(blkid -s UUID -o value $BOOTDEV)
rootuuid=$(blkid -s UUID -o value $ROOTDEV)

mkdir -p "$TMPDIR"/boot/extlinux
cat <<EOF > "$TMPDIR"/boot/extlinux/extlinux.conf
menu title Alpine Bananapi F3
timeout 50
default bpi-f3

label bpi-f3
	menu label Alpine bpi-f3
	kernel /vmlinuz-bpi-f3
	initrd /initramfs-bpi-f3
	fdt /dtbs-bpi-f3/spacemit/k1-bananapi-f3.dtb
	append earlycon=sbi rw root=UUID=$rootuuid rootfstype=ext4 rootwait console=ttyS0,115200 console=tty0 clk_ignore_unused swiotlb=65536

EOF

echo "Setting up inittab"
sed -i 's/^tty1.*/tty1::respawn:\/sbin\/agetty -L 115200 tty1 linux --login-pause --autologin root --noclear/' $TMPDIR/etc/inittab
sed -i 's/^#ttyS0/ttyS0/' $TMPDIR/etc/inittab
sed -i 's/^ttyS0.*/ttyS0::respawn:\/sbin\/agetty -L 115200 ttyS0 linux --login-pause --autologin root --noclear/' $TMPDIR/etc/inittab

echo "Finished, cleaning up"

