#!/bin/sh

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

if [ -b /dev/sda ]
then
	umount /dev/sda
	umount /dev/sda1
	umount /dev/sda2
	# gzip -d < 2021-01-11-raspios-buster-armhf-full.zip | dd of=/dev/sda bs=8192k status=progress
	# gzip -d < 2021-03-04-raspios-buster-armhf-full.zip | dd of=/dev/sda bs=8192k status=progress
	# unzip -p 2021-03-04-raspios-buster-armhf-full.zip | dd of=/dev/sda bs=8192k status=progress
	unzip -p 2022-01-28-raspios-bullseye-armhf.zip | dd of=/dev/sda bs=8192k status=progress
	echo "waiting for OS to figure out disks"
	sleep 60
	umount /dev/sda
	umount /dev/sda1
	umount /dev/sda2
	mount /dev/sda1 /mnt
	# cp *.txt /mnt
	touch /mnt/ssh
	sync
	umount /dev/sda1
	mount /dev/sda2 /mnt
	mkdir -p /mnt/home/pi/RaspiConfig
	mkdir -p /mnt/home/pi/bin
	cp showTemp *.local _profile *.conf *.txt *.sh *.tgz /mnt/home/pi/RaspiConfig/
	cp showTemp /mnt/home/pi/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/home/pi/.profile
	cp rc.local /mnt/etc/
	chown -R pi.pi /mnt/home/pi
	sync
	umount /dev/sda2
	sync
	dmesg -T | grep -vi sids | tail -20
	mount -r /dev/sda2 /mnt
	ls -ls /mnt/home/pi/RaspiConfig
	umount /dev/sda2
fi


