#!/usr/bin/env bash

# Exit script on first failure.
set -e

# Echo commands before executing them, by default to stderr.
set -x

VERSION="$1"
if [[ -z "${VERSION}" ]]; then
  >&2 echo "Must specify a version number like 1.2.3"
  exit 1
fi
readonly VERSION

# Exit on unset variable.
set -u

# Change directory to repository root.
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
readonly SCRIPT_DIR
cd "${SCRIPT_DIR}/.."

cd bin

readonly OUTPUT_DIR="${PWD}/../dist"
mkdir -p "${OUTPUT_DIR}"

for d in ./*_*; do
  FOLDER_NAME="$(basename "$d")"

  # Split FOLDER_NAME into an array with underscore as a delimiter.
  IFS="_" read -r -a FOLDER_PARTS <<< "${FOLDER_NAME}"

  OS="${FOLDER_PARTS[0]}"

  # Join remaining parts and remove spaces.
  FOLDER_PARTS=("${FOLDER_PARTS[@]:1}")
  ARCH="${FOLDER_PARTS[*]}"
  ARCH="${ARCH//[[:blank:]]}"

  pushd "$d"
  tar \
    --create \
    --compress \
    --file="${OUTPUT_DIR}/picoshare-v${VERSION}-${OS}-${ARCH}.tar.gz" \
    picoshare
  popd
done
