#! /bin/sh
#
# build-source-zip.sh
#
# Builds a zipfile suitable for distribution alongside binaries by excluding
# various bits and pieces that might leak a bit too much info and possibly
# infringe on copyrights.
#
# Must be run from the root of the source tree.
#

set -e

# set pwd so we can cd and still reference the zipfile
TARGET=$(pwd)/build/riskscape-src.zip
JAVA_HEADER=build/java-copyright-header.txt
JAVA_SRC_OUT=build/java-src
INI_HEADER=build/inifile-copyright-header.txt
INI_SRC_OUT=build/ini-src
EXPORTED_SRC=build/src

# only riskscape source - we have some monkey patched bits and pieces that
# come from other sources, so preserve their original licenses
JAVA_PATTERN='\.java$'
JAVA_EXCLUDE='/picocli/ /org/geotools/'

# Keep it to ini and properties within our src dirs - there are some others lying
# around that might not be ours to license
INI_PATTERN='\.properties$|\.ini$'

# get rid of an existing archive first
rm -f $TARGET || false

# git archive uses .git-attributes to control what's actually part of the
# exported source code, so we use that to create our source snapshot
git archive --worktree-attributes --prefix $EXPORTED_SRC/ --format tar HEAD | tar -x

# add in non-source files first
(cd $EXPORTED_SRC && find . |\
    grep -v -E "${JAVA_PATTERN}" |\
    grep -v -E "${INI_PATTERN}" |\
    xargs zip -q $TARGET)

# create java header
CURRENT_YEAR=`date +%Y`
echo '/*' > $JAVA_HEADER
sed 's/^/ * /' COPYRIGHT >> $JAVA_HEADER
echo ' *' >> $JAVA_HEADER
sed -e 's/^/ * /' -e "s/\${CURRENT_YEAR}/${CURRENT_YEAR}/" LICENSE-header >> $JAVA_HEADER
echo ' */' >> $JAVA_HEADER

# create java source avec header
# make the dirs first
find $EXPORTED_SRC | grep -E "${JAVA_PATTERN}"  | xargs dirname | uniq | sed s.^.$JAVA_SRC_OUT/. | xargs mkdir --parents
find $EXPORTED_SRC | grep -E "${JAVA_PATTERN}" | while read javafile ; do
  cat $JAVA_HEADER $javafile > $JAVA_SRC_OUT/$javafile
done
# now copy over the exclusions - this does some redundant copying, but is a bit simpler than stripping out the
# exclusions from the above
for excl in $JAVA_EXCLUDE; do
    find $EXPORTED_SRC | grep -E "${JAVA_PATTERN}" |grep -E "${excl}" | while read excluded ; do
	cp ${excluded} $JAVA_SRC_OUT/${excluded}
    done

done

# create ini/props header
echo '# ' > $INI_HEADER
sed 's/^/# /' COPYRIGHT >> $INI_HEADER
echo '# ' >> $INI_HEADER
sed -e 's/^/# /' -e "s/\${CURRENT_YEAR}/${CURRENT_YEAR}/" LICENSE-header >> $INI_HEADER
echo '# ' >> $INI_HEADER

# create java source avec header
# make the dirs first
find $EXPORTED_SRC | grep -E "${INI_PATTERN}" | xargs dirname | uniq | sed s.^.$INI_SRC_OUT/. | xargs mkdir --parents
find $EXPORTED_SRC | grep -E "${INI_PATTERN}" | while read inifile ; do
  cat $INI_HEADER $inifile > $INI_SRC_OUT/$inifile
done

# splodge now licensed files in to our source tarball
(cd ${JAVA_SRC_OUT}/${EXPORTED_SRC} && find . -type f | xargs zip -q $TARGET)
(cd ${INI_SRC_OUT}/${EXPORTED_SRC} && find . -type f | xargs zip -q $TARGET)
