#!/bin/bash

# copyright (c) 2005, 2006 Erik Jan Tromp <alphageek@slackware.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# Version 2 as published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License for more details.
#
#	http://www.fsf.org/licenses/gpl.html

TREEPREFIX=${1/%\//}
[ -z "$TREEPREFIX" ] && TREEPREFIX=.

for JIGDO in *.jigdo ; do
  if [ ! -r "$JIGDO" ] ; then
    echo "run this script in the same directory containing the .jigdo & .template files"
    break
  fi

  # [Image] info. ugly, but effective
  ISONAME=`sed -n 's,^Filename=,,p' $JIGDO`
  ISOTIME=`sed -n 's,^Filetime=,,p' $JIGDO`
  TEMPLATE=`sed -n 's,^Template=,,p' $JIGDO`
  TEMPLATE_MD5SUM=`sed -n 's,^Template-MD5Sum=,,p' $JIGDO`

  # sanity checks
  SKIP=no
  for TREESUFFIX in `sed -n "/\[Parts\]/,/^$/{s,.*:,,p}" $JIGDO \
  | sed 's,/.*,,' | sort -u` ; do
    if [ ! -d "$TREEPREFIX/$TREESUFFIX" ] ; then
      echo "directory \"$TREEPREFIX/$TREESUFFIX\" not found. skipping"
      SKIP=yes
    fi
  done
  [ "$SKIP" = "yes" ] && continue
  if [ -z "$ISONAME" -o -z "$TEMPLATE" -o -z "$TEMPLATE_MD5SUM" ] ; then
    echo "\"$JIGDO\" appears to be damaged. skipping"
    continue
  fi
  if [ ! -r "$TEMPLATE" ] ; then
    echo "\"$TEMPLATE\" appears to be missing. skipping"
    continue
  fi
  if [ "`jigdo-file md5sum --report quiet $TEMPLATE \
  | sed -n 's, .*,,p'`" != "$TEMPLATE_MD5SUM" ] ; then
    echo "\"$TEMPLATE\" appears to be damaged. skipping"
    continue
  fi
  if [ -r "$ISONAME" ] ; then
    echo "\"$ISONAME\" already exists. verifying"
    jigdo-file verify --template $TEMPLATE --image $ISONAME
    continue
    # more needs to be done here. if verification fails, force a rebuild
  fi

  # assorted prep work
  FILELIST=`basename $TEMPLATE .template`.filelist
  sed -n "/\[Parts\]/,/^$/{s,.*:,$TREEPREFIX/,p}" $JIGDO > $FILELIST
  mkdir -p `dirname $ISONAME`

  # all the prep work is done. let's make an iso!
  jigdo-file make-image --jigdo $JIGDO --template $TEMPLATE \
  --image $ISONAME --files-from $FILELIST

  # let's be tidy
  if [ $? -eq 0 ] ; then
    touch $ISONAME --date "$ISOTIME"
    rm $FILELIST
  fi
done

