#!/usr/bin/env bash

set -e

cd "${BASH_SOURCE%/*}/.."

USAGE="usage: bin/package [-v PACKAGE_VERSION]"

while getopts ":v:h" opt; do
  case $opt in
    v)
      PKG_VERSION=$OPTARG
      ;;
    h)
      echo $USAGE >&2
      exit
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      echo $USAGE >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument" >&2
      echo $USAGE >&2
      exit 1
      ;;
  esac
done

if [ -z "$PKG_VERSION" ]; then
  PKG_VERSION=$(git describe --tag --exact-match)
fi

if [[ $(php --version) = PHP\ 5.3* ]]; then
  PKG_VERSION=${PKG_VERSION}-php53
fi

echo "Packaging $PKG_VERSION"

mkdir -p dist || exit 1

./bin/build || exit 1
chmod +x *.phar

echo "Creating tarballs"

# Support BSD tar because OS X :(
if [[ $(tar --version) = bsdtar* ]]; then
  tar -s "/.*/psysh/" -czf dist/psysh-${PKG_VERSION}.tar.gz psysh.phar
  tar -s "/.*/psysh/" -czf dist/psysh-${PKG_VERSION}-compat.tar.gz psysh-compat.phar
else
  tar --transform "s/.*/psysh/" -czf dist/psysh-${PKG_VERSION}.tar.gz psysh.phar
  tar --transform "s/.*/psysh/" -czf dist/psysh-${PKG_VERSION}-compat.tar.gz psysh-compat.phar
fi
