#!/bin/bash

#verify files
echo Making sure all files are present...
if ! [ -s rc.local ]; then
	echo rc.local file is missing, aborting
	exit -1;fi

if ! [ -s watchdog.sh ]; then
	echo watchdog.sh file is missing, aborting
	exit -1;fi

if ! [ -s raspbian.img ]; then
	echo raspbian.img file is missing, aborting
	exit -1;fi

if ! [ -s pixel.iso ]; then
	echo pixel.iso file is missing, aborting
	exit -1;fi

#find the SD card: assumed to be the first drive that is not mounted, greater than 10G, removable, and not read only.
echo Finding the SD card...
umount -a 2>/dev/null

for drive in `ls /sys/block`; do
	if [ `cat /sys/block/$drive/size` -lt 20000000 ]; then size=1; else size=0; fi
	removable=$(( `cat /sys/block/$drive/removable` ))
	if [ $removable -eq 1 ]; then removable=0; else removable=1; fi
	ro=`cat /sys/block/$drive/ro`
	mounted=0
	mount | grep -q $drive && mounted=1
	if [ $(( $size | $removable | $ro | $mounted )) -eq 0 ]; then
		SD=/dev/$drive
		break; fi
done

if ! [ -v SD ]; then
	echo SD card not found, possibly because some partitions automounted.
	echo Click on the eject icon to unmount them.
	exit -1; fi

echo SD card is $SD, waiting 20 seconds in case you want to abort...
sleep 20
#copy raspbian, re-partition, then copy pixel
echo Copying Raspbian. This may take a while...
dd if=raspbian.img of=$SD bs=1M
echo Re-partitioning disk...
echo mkpart primary hfs -4000 -0 | parted $SD
sfdisk --change-id $SD 3 0
echo resizepart 2 -4001 | parted $SD
#waiting for partition change to take effect
sleep 20
e2fsck -f -y "$SD"2 1>/dev/null 2>/dev/null
resize2fs "$SD"2
echo Copying Pixel. This may take a while...
dd if=pixel.iso of="$SD"3 bs=1M

#config file edits
echo Editing configuration files...
mount "$SD"1 /media
#stop auto-resize on first boot
sed -i 's| quiet init=/usr/lib/raspi-config/init_resize.sh||' /media/cmdline.txt
#boot partition edits
touch /media/ssh
echo dtoverlay=dwc2 >> /media/config.txt
umount /media
#remove auto-resize files
mount "$SD"2 /media
rm /media/etc/init.d/resize2fs_once
rm /media/etc/rc3.d/S01resize2fs_once
#root partition edits
ln -s /lib/systemd/system/multi-user.target /media/etc/systemd/system/default.target
cp rc.local /media/etc
chmod 755 /media/etc/rc.local
cp watchdog.sh /media/etc
chmod 755 /media/etc/watchdog.sh
echo CONF_SWAPSIZE=0 > /media/etc/dphys-swapfile
echo dwc2 >> /media/etc/modules
echo libcomposite >> /media/etc/modules
echo interface usb0 >> /media/etc/dhcpcd.conf
echo static ip_address=10.0.0.1 >> /media/etc/dhcpcd.conf
echo static routers=10.0.0.2 >> /media/etc/dhcpcd.conf
echo static domain_name_servers=8.8.8.8 8.8.4.4 >> /media/etc/dhcpcd.conf
echo allow-hotplug usb0 >> /media/etc/network/interfaces
echo iface usb0 inet manual >> /media/etc/network/interfaces
umount /media
sync
echo SD card is now ready for the Pi Zero.
exit 0
