#!/bin/bash

set -e # exit when any command fails

BASE_DIR=$(git rev-parse --show-toplevel)
BIN_DIR="$BASE_DIR/node_modules/.bin"
BUILDS_DIR="$BASE_DIR/builds"
TMP_DIR="$BASE_DIR/.tmp_build"

NODE_VERSION="node8.9.0"
TARGETS=(
  "macos"
  "linux"
  "win"
)

PATHS=(
  "bin" "src" "starter" "themes"
  "package.json" "yarn.lock"
)

rm -rf $TMP_DIR $BUILDS_DIR
mkdir $TMP_DIR

for path in "${PATHS[@]}"
do
  cp -r $BASE_DIR/$path $TMP_DIR
done

cd $TMP_DIR
yarn install --production

  # temporary for linking timber ui
  # yarn link @timberio/ui
  # cd node_modules/@timberio/ui
  # rm -r node_modules && yarn install --production
  # cd $TMP_DIR

for target in "${TARGETS[@]}"
do
  ZIP="$BUILDS_DIR/gitdocs-$target.zip"

  if [ "$target" == "win" ]; then
    OUT=$BUILDS_DIR/$target.exe
  else
    OUT=$BUILDS_DIR/$target
  fi

  $BIN_DIR/pkg . \
    --targets $NODE_VERSION-$target \
    --output $OUT

  zip -j $ZIP $OUT.exe
done

rm -r $TMP_DIR
