#!/bin/bash
# Simple script to download a grml iso image to use with grml-rescueboot
# Needs the debian keyring, gpg, wget and sha1sum
# Licensed under GPL v2+

usage() {
	echo "Usage: $0 [-f] [-a <32|64|96>] [-t <small|full>]" >&2
}

set -e

isotype=full
bitwidth=auto
force=0

while getopts ":a::t::f" opt ; do
	case $opt in
		a)
			if [ $OPTARG = 32 -o $OPTARG = 64 -o $OPTARG = 96 ] ; then
				bitwidth=$OPTARG
			else
				echo "Invalid value '$OPTARG'" >&2
				fail=1
			fi
			;;
		t)
			if [ $OPTARG = full -o $OPTARG = small ] ; then
				isotype=$OPTARG
			else
				echo "Invalid value '$OPTARG'" >&2
				fail=1
			fi
			;;
		f)
			force=1
			;;
		\?)
			echo "Invalid Option: -$OPTARG" >&2
			fail=1
			;;
		:)
			echo "Option -$OPTARG requires an argument" >&2
			fail=1
			;;
	esac
done

if [ -n "$fail" ] ; then
	usage
	exit 1
fi

if [ "$bitwidth" = auto ] ; then 
	arch=$(uname -m)
	case $arch in
		i?86)
			bitwidth=32
			;;
		x86_64)
			bitwidth=64
			;;
		*)
			echo "unknown architecture '$arch', please specify -a flag"
			usage
			exit 1
			;;
	esac
fi

echo "Finding out latest iso image..."
date=$(wget --quiet -O- http://download.grml.org/ | sed --regex -n 's/.*grml[0-9]{2}-(full|small)_([0-9]{4}\.[0-9]{2})\.iso.*/\2/p' | sort | tail -1)

if [ -z "$date" ] ; then
	echo "Could not find out latest iso" >&2
	exit 1
fi

isoname=grml${bitwidth}-${isotype}_${date}.iso

if [ -f $isoname ] ; then
	echo "Found local $isoname, skipping download (use -f to force download)"
else
	echo "Downloading $isoname ..."
	wget -O $isoname http://download.grml.org/$isoname
fi

sig=`mktemp`

echo "Verifying iso..."
wget --quiet -O $sig http://download.grml.org/${isoname}.asc

if ! gpgv --keyring /usr/share/keyrings/debian-keyring.gpg $sig $isoname ; then
	echo "Iso file will be left in ${isoname}.untrusted"
	mv $isoname ${isoname}.untrusted
	rm $sig
	exit 1
fi

rm $sig

echo "File is OK, move ./$isoname to /boot/grml and run update-grub"

