#!/bin/sh

set -e

if [ $# -ne 3 ]; then
  echo "Error: 3 parameters are required."
  exit 1
fi

if [ "$1" != "--upstream-version" ]; then
  echo "Error: First parameter needs to be --upstream-version."
  exit 1
fi

VERSION=$2
ISOFILE=$3

ORGDIR=`pwd`

cd `dirname $ISOFILE`
if ! wget -O - http://download.virtualbox.org/virtualbox/$VERSION/SHA256SUMS | grep iso | sha256sum -c --strict -; then
  echo "Error: checksum doesn't match."
  exit 1
fi
cd $ORGDIR

PACKAGE_NAME=`awk '/^Source: / { print $2 }' debian/control`

if [ -z "$PACKAGE_NAME" ]; then
  echo "Error: couldn't determine package name."
  exit 1
fi

TMP=`mktemp -d`

if [ -z "$TMP" ]; then
  echo "Error: couldn't create a tmp dir."
  exit 1
fi

trap 'rm -r $TMP' EXIT

mkdir $TMP/${PACKAGE_NAME}-$VERSION
mv $ISOFILE $TMP/${PACKAGE_NAME}-$VERSION/
cd $TMP
tar czf ${PACKAGE_NAME}_$VERSION.orig.tar.gz ${PACKAGE_NAME}-$VERSION
mv ${PACKAGE_NAME}_$VERSION.orig.tar.gz $ORGDIR/../
cd $ORGDIR
