#!/bin/sh

if [ `whoami` != "root" ]
then
	echo "$0 must be invoked as root"
	exit 1
fi

DEV=$1
if [ "x$DEV" == "x" ]
then
	echo "Error: device missing"
	echo "Usage: $0 device (sda, ...)"
	exit 1
fi

if [ ! -b /dev/$DEV ]
then
	echo "Error: $DEV is not a device"
	echo "Usage: $0 device (sda, ...)"
	exit 1
fi

# DEV=sda
P1=1
P2=2

ls -ls /dev/$DEV
ls -ls /dev/$DEV$P1
ls -ls /dev/$DEV$P2

if [ -b /dev/$DEV ]
then
	umount /dev/$DEV
	umount /dev/$DEV$P1
	umount /dev/$DEV$P2
	# gzip -d < 2021-01-11-raspios-buster-armhf-full.zip | dd of=/dev/$DEV bs=8192k status=progress
	# gzip -d < 2021-03-04-raspios-buster-armhf-full.zip | dd of=/dev/$DEV bs=8192k status=progress
	# unzip -p 2021-03-04-raspios-buster-armhf-full.zip | dd of=/dev/$DEV bs=8192k status=progress
	# unzip -p ../2022-01-28-raspios-bullseye-armhf.zip | dd of=/dev/$DEV bs=8192k status=progress
	# For Le Potato:
	# xzcat ../2022-09-22-raspbian-bullseye-arm64+aml-s905x-cc.img.xz | dd of=/dev/$DEV bs=8192k status=progress
	# For 32-bit Pi:
	# xzcat ../2022-09-22-raspios-bullseye-armhf.img.xz | dd of=/dev/$DEV bs=8192k status=progress
	xzcat ../2023-02-21-raspios-bullseye-armhf.img.xz | dd of=/dev/$DEV bs=8192k status=progress
	echo "waiting for OS to figure out disks"
	sleep 20
	umount /dev/$DEV
	umount /dev/$DEV$P1
	umount /dev/$DEV$P2
	mount /dev/$DEV$P1 /mnt
	# cp *.txt /mnt
	touch /mnt/ssh
	sed 's/115200/9600/g' /mnt/cmdline.txt > cmdline.txt
	chmod 0755 cmdline.txt
	/usr/bin/mv cmdline.txt /mnt/cmdline.txt
	echo "enable_uart=1" >> /mnt/config.txt
	echo "gpu_mem=16" >> /mnt/config.txt
	echo "pi:`echo raspberry | openssl passwd -6 -stdin`" > /mnt/userconf.txt
	sync
	umount /dev/$DEV$P1
	mount /dev/$DEV$P2 /mnt
	mkdir -p /mnt/apps/RaspiConfig
	mkdir -p /mnt/apps/bin
	cp *.txt *.sh /mnt/apps/RaspiConfig/
	cp show-temp /mnt/apps/bin
	if [ ! -f /mnt/etc/wpa_supplicant/wpa_supplicant.conf.orig ]
	then
		mv /mnt/etc/wpa_supplicant/wpa_supplicant.conf /mnt/etc/wpa_supplicant/wpa_supplicant.conf.orig
	fi
	cp -p wpa_supplicant.conf /mnt/etc/wpa_supplicant/wpa_supplicant.conf
	if [ ! -f /mnt/etc/rc.local.orig ]
	then
		mv /mnt/etc/rc.local /mnt/etc/rc.local.orig
	fi
	cat _profile >> /mnt/apps/_profile
	cp rc.local /mnt/etc/
	chown -R pi.pi /mnt/apps
	sync
	umount /dev/$DEV$P2
	sync
	dmesg -T | grep -vi sids | tail -20
	mount -r /dev/$DEV$P2 /mnt
	ls -ls /mnt/apps/RaspiConfig
	umount /dev/$DEV$P2
fi


