#!/usr/bin/env bash

set -euxo pipefail

version=${1#"refs/tags/"}
os=$2
target=$3
src=`pwd`
dist=$src/target/dist
bin=imdl

echo "Packaging $bin $version for $target..."

test -f Cargo.lock || cargo generate-lockfile

echo "Building $bin..."

case $os in
  ubuntu-latest)
    sudo apt install help2man musl-tools
    ;;
  macos-latest)
    brew install help2man
    ;;
  windows-latest)
    ;;
esac

RUSTFLAGS='--deny warnings --codegen target-feature=+crt-static' \
  cargo build --bin $bin --target $target --release
executable=target/$target/release/$bin

if [[ $os == windows-2016 ]]; then
  executable=$executable.exe
fi

echo "Building completions..."
cargo run --package gen -- --bin $executable completion-scripts

echo "Generating readme..."
cargo run --package gen -- --bin $executable readme

echo "Copying static files..."
mkdir $dist
cp -r \
  $executable \
  CONTRIBUTING \
  Cargo.lock \
  Cargo.toml \
  LICENSE \
  $dist

echo "Copying generated files..."
cp -r \
  target/gen/README.md \
  target/gen/completions \
  $dist

if [[ $os != windows-latest ]]; then
  echo "Building man pages..."
  cargo run --package gen -- --bin $executable man
  cp -r target/gen/man $dist/man
fi

cd $dist
echo "Creating release archive..."
case $os in
  ubuntu-latest | macos-latest)
    archive=$dist/$bin-$version-$target.tar.gz
    tar czf $archive *
    echo "::set-output name=archive::$archive"
    ;;
  windows-latest)
    archive=$dist/$bin-$version-$target.zip
    7z a $archive *
    echo "::set-output name=archive::`pwd -W`/$bin-$version-$target.zip"
    ;;
esac
