#!/bin/bash

USAGE() {
    printf 'Usage: %s [VERSION]\n' \
        "${0##*/}"
}

check_required_binaries() {
    local BIN MISSING=()
    for BIN; do
        if ! type -t "$BIN" &>/dev/null; then
            MISSING+=("$BIN")
        fi
    done
    if [[ ${#MISSING[@]} -gt 0 ]]; then
        printf 'Error: You are missing required programs:\n' >&2
        for BIN in "${MISSING[@]}"; do
            printf -- '- %s\n' "$BIN" >&2
        done
        exit 2
    fi
}

check_required_binaries \
    gzip \
    mkdir \
    realpath \

WORKDIR=${0%/*}
BASEDIR=$(realpath -- "$WORKDIR/..")
cd "$BASEDIR" || exit

RELEASESDIR=$BASEDIR/releases

PROJECT=Chicken-Ipsum
VERSION=$1
if [[ -z $VERSION ]]; then
    if [[ -e .git ]]; then
        check_required_binaries git
        VERSION=$(git describe --tags)
        VERSION=${VERSION#[a-z]}
    fi
fi
if [[ -z $VERSION ]]; then
    USAGE >&2
    exit 1
fi
DIRBASE=$PROJECT-$VERSION
# XXX CPAN requires either .tar.gz or .zip
TAR=$RELEASESDIR/$DIRBASE.tar.gz

if [[ ! -e META.json || ! -e META.yml ]]; then
    perl Makefile.PL &&
    cp MYMETA.json META.json &&
    cp MYMETA.yml META.yml || exit
fi

mkdir -p -- "$RELEASESDIR" &&
git archive \
    --format=tar \
    --prefix="$DIRBASE/" \
    --add-file=META.json \
    --add-file=META.yml \
    -- \
    HEAD |
gzip -9 > "$TAR" &&
printf 'Created %s\n' "$TAR"
