#!/bin/sh

USAGE="$0 [-m] <name> <url>

pack the build directory into an archive for the site address <url> and
print the path of the archive. run from the site root.

the archive is written to dist/ as <build dir>-<name>-<version>.tar.gz. it
holds the build directory under its own name. the version comes from
get_version.sh -f.

the generated pages contain absolute urls built from site_url in config.txt.
when <url> is a different address, site_url is replaced with <url> in every
html file of a copy of the build directory. the build directory itself is
not changed.

options:
    -m, --make      run make_site.py -c first
    -h, --help      print this help

positional:
    name            symbolic name of the target, such as test or prod
    url             public address of the target, without a trailing slash
"

MAKE=0
NAME=
URL=

while [ "$#" != 0 ]
do
    case $1 in
        -m|--make) MAKE=1 ;;
        -h|--help) echo "$USAGE"; exit 0 ;;
        -*) echo "unrecognized option '$1'" >&2; exit 1 ;;
        *)
            if [ -z "$NAME" ] ; then
                NAME="$1"
            elif [ -z "$URL" ] ; then
                URL="$1"
            else
                echo "unrecognized argument '$1'" >&2
                exit 1
            fi
            ;;
    esac
    shift
done

if [ -z "$NAME" ] || [ -z "$URL" ] ; then
    echo "missing name or url" >&2
    exit 1
fi

if [ ! -f config.txt ] ; then
    echo "no config.txt in the current directory" >&2
    exit 1
fi

TROOT="$(dirname "$0")"
URL="${URL%/}"

if [ "$MAKE" = 1 ] ; then
    "$TROOT"/make_site.py -c || exit 1
fi

# values from config.txt, without surrounding whitespace or trailing slashes
SITE_URL=$(sed -n 's/^site_url:[[:space:]]*//p' config.txt |
    sed 's|[/[:space:]]*$||') &&
if [ -z "$SITE_URL" ] ; then
    echo "no site_url in config.txt" >&2
    exit 1
fi

BUILD_DIR=$(sed -n 's/^build_dir:[[:space:]]*//p' config.txt |
    sed 's|[/[:space:]]*$||')
: "${BUILD_DIR:=www}"
BUILD_NAME=$(basename "$BUILD_DIR")

if [ ! -d "$BUILD_DIR" ] ; then
    echo "no build directory '$BUILD_DIR', build first or use -m" >&2
    exit 1
fi

VERSION=$("$TROOT"/get_version.sh -f) &&
ARCHIVE="dist/$BUILD_NAME-$NAME-$VERSION.tar.gz" &&
mkdir -p dist &&

STAGE=$(mktemp -d) || exit 1
trap 'rm -rf "$STAGE"' EXIT

cp -Rp "$BUILD_DIR" "$STAGE/$BUILD_NAME" &&

if [ "$URL" != "$SITE_URL" ]
then
    # dots in the url are literal, not sed wildcards
    PATTERN=$(printf '%s' "$SITE_URL" | sed 's/[.]/\\./g') &&
    find "$STAGE" -type f -name '*.html' |
    while IFS= read -r FILE
    do
        sed "s|$PATTERN|$URL|g" "$FILE" > "$FILE.tmp" &&
        mv "$FILE.tmp" "$FILE" ||
        exit 1
    done
fi &&

tar -czf "$ARCHIVE" \
    --no-xattrs --no-mac-metadata \
    --exclude='.DS_Store' \
    -C "$STAGE" "$BUILD_NAME" &&

echo "$ARCHIVE"
