#!/bin/sh

set -ex

VERSION=$2
ORIG_ZIP=`readlink -f ../ldraw-parts_$VERSION.orig.tar.xz`
ZIP_LOC=`dirname "${ORIG_ZIP}"`
REAL_DIR="${ZIP_LOC}/ldraw-parts-${VERSION}+ds"
REAL_TAR="${ZIP_LOC}/ldraw-parts_${VERSION}+ds.orig.tar.xz"
REAL_DIR_BASE=`basename "$REAL_DIR"`

mkdir -p "$REAL_DIR"

# extract and remove the zip
tar -C "${REAL_DIR}" -xf "${ORIG_ZIP}"
rm "${ORIG_ZIP}"

# recover mklist.c and headers from mklist1_6.zip
unzip -q "${REAL_DIR}/mklist1_6.zip" mklist.c include/*.h -d "${REAL_DIR}"

# remove all zip archives (they contain compiled *.exe and old source)
# remove mklist.exe
rm "${REAL_DIR}/"*.zip "${REAL_DIR}/mklist.exe"

# repack source tarball
# gz would be 47% larger than xz
XZ_OPT=-v9e tar --remove-files --directory "${ZIP_LOC}" -cJf "${REAL_TAR}" "${REAL_DIR_BASE}"

exit 0
