#!/usr/bin/env bash
# Usage: script/package <os> <arch> <version>
#
# Packages the project as a release asset and prints the archive's filename.
set -e

os="${1?}"
arch="${2?}"
version="${3?}"

release="hub-${os}-${arch}-${version}"

case "$os" in
  darwin | freebsd | linux | netbsd | openbsd | solaris | windows ) ;;
  * ) echo "unsupported OS: $os" >&2; exit 1 ;;
esac

case "$arch" in
  386 | amd64 ) ;;
  * ) echo "unsupported arch: $arch" >&2; exit 1 ;;
esac

export GOOS="$os"
export GOARCH="$arch"

tmpdir="tmp/${release}"
rm -rf "$tmpdir"

exename="${tmpdir}/bin/hub"
[ "$os" != "windows" ] || exename="${exename}.exe"
mkdir -p "${exename%/*}"
script/build -o "$exename"

crlf() {
  sed $'s/$/\r/' "$1" > "$2"
}

if [ "$os" = "windows" ]; then
  crlf README.md "${tmpdir}/README.txt"
  crlf LICENSE "${tmpdir}/LICENSE.txt"
  crlf man/hub.1.html "${tmpdir}/hub.html"
  crlf script/install.bat "${tmpdir}/install.bat"
else
  cp -R README.md LICENSE etc "$tmpdir"
  mkdir -p "${tmpdir}/share/man/man1"
  cp man/hub.1 "${tmpdir}/share/man/man1"
  cp script/install.sh "${tmpdir}/install"
  chmod +x "${tmpdir}/install"
fi

if [ "$os" = "windows" ]; then
  file="${PWD}/${tmpdir}.zip"
  rm -f "$file"
  pushd "$tmpdir" >/dev/null
  zip -r "$file" * >/dev/null
else
  file="${PWD}/${tmpdir}.tgz"
  rm -f "$file"
  pushd "${tmpdir%/*}" >/dev/null
  tar -czf "$file" "$release"
fi

echo "$file"
