#!/bin/sh
#
# Rip debs out of downloaded isos for use in pre-populating apt-cacher
# caches
#
# Written by Steve Beattie <sbeattie@ubuntu.com>
# Copyright 2008 Canonical Ltd.
# Licensed under the GNU General Public License, version 3.


set -e

DIR=${HOME}/iso
if [ ! -z "$1" ] ; then
	DIR="$1"
fi

CACHEDIR=${DIR}/cache
echo "CACHEDIR=${CACHEDIR}"
echo

ISOINFO=/usr/bin/isoinfo

if ! mkdir -p ${CACHEDIR} ; then
	echo "failed to create cache directory ${CACHEDIR}"
	echo "permissions problem?"
	exit 1
fi

if [ ! -x ${ISOINFO} ] ; then
	echo "Please install the isoinfo package in order to extract files from isos"
	echo "(On ubuntu, 'sudo apt-get install genisoimage' will get it."
	exit 1
fi

has_joliet()
{
	local iso="$1"
        ! ${ISOINFO} -d -i "${iso}" | grep -q "^NO Joliet"
}


find ${DIR} -name "*.iso" -print | while read isoname ; do
	if ! has_joliet "${isoname}" ; then
		continue
	fi

	echo "Pulling debs off of ${isoname} ..."
	${ISOINFO} -f -J -i "${isoname}" | grep ".deb$" | while read iso_deb ; do
		debname=$(basename "${iso_deb}")
		if [ ! -f "${CACHEDIR}/${debname}" ] ; then
			if ${ISOINFO} -J -x "${iso_deb}" -i "${isoname}" > "${CACHEDIR}/${debname}" ; then
				:
			else
				rm "${CACHEDIR}/${debname}"
			fi
		fi
	done
done	
