#!/bin/bash

set -e

test $# == 3

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

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

ORIGTAR="$(echo "$3" | sed -e 's/\.orig/+repack.orig/')"
ORIGDIR="lhapdf-$VER+repack.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 cteq61.LHpdf MRST2004nlo.LHgrid \
	cteq6ll.LHpdf GRV98nlo.LHgrid MRST2001nlo.LHgrid; do
	wget "$URL/pdfsets/$VER/$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"

rm -f "$3"
