#!/bin/bash

set -e

test $# == 3

URL="http://www.hepforge.org/archive/lhapdf"
VER="$2"

UPTAR="lhapdf-$VER.tar.gz"
UPDIR="lhapdf-$VER"

ORIGTAR="$3"
ORIGDIR="lhapdf-$VER.orig"

DESTDIR="$(dirname "$ORIGTAR")"

test ! -f "$DESTDIR/$UPTAR" && wget "$URL/$UPTAR" -O "$DESTDIR/$UPTAR"
test -d "$UPDIR" && rm -rf "$UPDIR"

tar -xf "$DESTDIR/$UPTAR"

# get PDFsets

mkdir -p "$UPDIR/PDFsets"

for pdf in cteq5l.LHgrid cteq61.LHgrid CT10.LHgrid GRV98nlo.LHgrid \
	MRST2001nlo.LHgrid cteq6ll.LHpdf; do
	wget "$URL/pdfsets/current/$pdf" -O "$UPDIR/PDFsets/$pdf"
done

# remove generated source files
rm -f "$UPDIR/pyext/lhapdf.py" "$UPDIR/pyext/lhapdf_wrap.cc" \
	"$UPDIR/src/parmsetup.inc"

mv "$UPDIR" "$ORIGDIR"

test -e "$ORIGTAR" && rm -f "$ORIGTAR"
GZIP=-9 tar --remove-files -zcf "$ORIGTAR" "$ORIGDIR"
