#!/bin/sh
# flashybrid flash update program
# This script can assume a full debian system is available.

CONFDIR=/etc/flashybrid

set -e

. $CONFDIR/config

if [ -e $CONFDIR/partial ]; then
	for item in $(grep -v '^#' $CONFDIR/partial); do
		if [ -z "$DISKMOUNT" ]; then
			echo "error: DISKMOUNT is not set in /etc/flashybrid/config, cannot use partial directories" >&2 
			exit 1
		fi
	
		# Glob wildcards relative to the disk so they expand.
		for file in $(ls -1 $DISKMOUNT/$item | sed "s:^$DISKMOUNT::"); do
			DESTDIR=$FLASHMOUNT/$(dirname $file).partial
			if [ -e $DISKMOUNT/$file ]; then
				echo "Updating $file"
				mkdir -p $DESTDIR
				mkdir -p $FLASHMOUNT/$(dirname $file)
				rsync -a $DISKMOUNT/$file $DESTDIR/
			else
				echo "Skipping missing $file"
			fi
			# Mark the partial dir as such.
			touch $DESTDIR/.partial
		done
	done

	# Now sweep through the partial directories and clean up any
	# obsolete files.
	for dir in $(grep -v '^#' $CONFDIR/partial | sed 's:/.[^/]*$::' | sort | uniq); do
		for file in $(find $FLASHMOUNT/$dir.partial -mindepth 1 -maxdepth 1 -printf "%f\n"); do
			if [ "$file" != ".partial" -a ! -e $DISKMOUNT/$dir/$file ]; then
				echo "Deleting obsolete $file from $FLASHMOUNT/$dir.partial"
				rm -f $FLASHMOUNT/$dir.partial/$file
			fi
		done
	done
fi
