#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ROOT_DIR="$(realpath "$SCRIPT_DIR/..")"
cd "$ROOT_DIR"


# Configuration
NODE_VERSION="10.12.0"

# Update packages
{
    echo "Updating node packages ..."
    npm install
}

# Test the application to make sure it works
{
    echo "Testing application ..."
    if ! "$SCRIPT_DIR/run" --test-dist ; then
        echo "ERROR: application failed test-run"
        exit 1
    fi
}

# Make distribution directory
{
    DIST_DIR="$(realpath "$ROOT_DIR/_dist" || true)"
    rm -rf "$DIST_DIR"
    mkdir -p "$DIST_DIR"
}

# Archive node application
{
    echo "Updating node executables ..."
    NODE_URL="http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz"
    NODE_SDK_DIR="$ROOT_DIR/sdks/Node-v$NODE_VERSION"
    mkdir -p "$NODE_SDK_DIR"
    NODE_ZIP="$NODE_SDK_DIR/$(basename "$NODE_URL")"
    if [[ ! -f "$NODE_ZIP" ]]; then
        curl -qqL "$NODE_URL" -o "$NODE_ZIP"
    fi
    cp -f "$NODE_ZIP" "$DIST_DIR/node.tar.gz"
}

# Archive node packages
{
    # Note the use of "-h" for tar to dereference links!
    echo "Packaging node packages ..."
    tar -chzf "$DIST_DIR/node_modules.tar.gz" "node_modules"
}

# Archive application files
{
    echo "Packaging application files ..."
    # Get a list of files in git, and a list of files not yet committed to git (excluding files in .gitignore)
    git ls-files -z                             | xargs -0r tar -cf "$DIST_DIR/application.tar" --
    git ls-files -z --others --exclude-standard | xargs -0r tar -rf "$DIST_DIR/application.tar" --
}

# Copy required "install" and "run" scripts
{
    # Convert files to unix line-endings
    echo "Packaging scripts ..."
    while IFS= read -r -d '' FILE; do
        dos2unix -q -n "$FILE" "$DIST_DIR/$(basename "$FILE")"
    done <  <(find "$ROOT_DIR/templates" -type f -print0)
}
