#!/bin/sh -e

options=$(getopt -s sh -n $0 f:t:o: "$@")
if [ $? -ne 0 ]; then
    echo >&2 "Usage: $0 [-f flavour] [-t template] [-o output] manifests..."
	exit 1
fi

flavour=regular
template=hd-64MB.img.gz
output=hd.img
for option in $options; do
    case "$option" in
        -f) shift; flavour=$1; shift;;
        -t) shift; template=$1; shift;;
        -o) shift; output=$1; shift;;
        --) break;;
    esac
done
manifests="pack.manifest"

if [ "$flavour" = "" ]; then
    echo >&2 "$0: you must specify a flavour (try 'regular')"
    exit 1
fi
if [ "$template" = "" ]; then
    echo >&2 "$0: you have to supply a template file (try something in 'hd-64MB.img.gz')"
    exit 1
fi
if [ "$manifests" = "" ]; then
    echo >&2 "$0: you have to supply at least one manifest (try something in 'manifests')"
    exit 1
fi

ROOT=$PWD/source/$flavour
export ROOT

echo "Flavour:       $flavour"
echo "Template file: $template"
echo "Output image:  $output"
echo "Manifests:     $manifests"


mnt=mnt
mkdir -p $mnt
zcat $template > $output
mount $output $mnt -o loop,offset=512
trap "umount $mnt" EXIT

for mf in $manifests; do
    echo "Running manifest $mf"

    cd $mnt
    . ../manifests/$mf
    cd ..
done
