#!/bin/sh

################################################################################
#
# Reformat mtd1 (root, usr and log) on an Affinity and reload the firmware
#
################################################################################

RSYNC_SRC="rsync://rsync.guralp.com/platinum-stable/CMG-DAS/"

set -x
hwclock -w

# Attempt to save the clock's temperature-training data
ubiattach /dev/ubi_ctrl -m 1
if mount -t ubifs /dev/ubi0_0 /mnt ; then
	cp /mnt/var/lib/das-in/clock-free.table .
	umount /mnt
fi
ubidetach -d 0 /dev/ubi_ctrl

# Format the device
ubiformat -y /dev/mtd1

# Make the volumes
ubiattach /dev/ubi_ctrl -m 1
ubimkvol /dev/ubi0 -N root -s 584MiB
ubimkvol /dev/ubi0 -N usr -s 256MiB
ubimkvol /dev/ubi0 -N log -s 64MiB

# Mount them
mount -t ubifs /dev/ubi0_0 /mnt
mkdir /mnt/boot /mnt/usr /mnt/var /mnt/var/log
mount -t ubifs /dev/ubi0_1 /mnt/usr
mount -t ubifs /dev/ubi0_2 /mnt/var/log

# Load the firmware
mkdir -p /mnt/etc/conf.local
rsync -rlptDzv --chmod=ugo+r,+X --exclude '/boot/**' "$RSYNC_SRC" /mnt/
touch /mnt/.magic_upgrade

# Recover the temperature-training data
if [ -f clock-free.table ] ; then
	mkdir -p /mnt/var/lib/das-in/
	mv clock-free.table /mnt/var/lib/das-in/
	chmod 644 /mnt/var/lib/das-in/clock-free.table
fi

# Tidy up
umount /mnt/var/log
umount /mnt/usr
umount /mnt
sync
set +x
echo ===================================================
echo === Please power-cycle the Affinity to continue ===
echo ===================================================
rm $0
