#!/usr/bin/env bash
set -e
set -x

# This script is executed from the $REPO/jenkinsbuild folder, but we need to get to the repo root
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE:-0}")" &>/dev/null && pwd)

# quiet down annoying npm spew
npm config set fund false
npm config set audit false

PACKAGENAME=corellium-cli
CORES=8
EXTRASDIR=/home/corellium/compute-extras
STAGINGDIR=$(mktemp -d /tmp/corellium-packaging-staging-compute-XXXXXXXXXX)
SYSROOT=/opt/ubuntu-arm64-sysroot
TMPROOT=${STAGINGDIR}/build-sysroot
DESTDIR=${STAGINGDIR}/${PACKAGENAME}
OUTPUTDIR=/home/corellium/output

mkdir -p ${OUTPUTDIR}
mkdir -p ${TMPROOT}
cp -a ${SYSROOT}/* ${TMPROOT}/

echo "Starting build for ${PACKAGENAME} on ${GIT_BRANCH}"
echo "-------------------------------------- current directory when starting build"
pwd

function build() {
    # To start the build we need to move up one level from $repo/jenkinsbuild to just the $repo root
    cd "$SCRIPT_DIR"
    cd ..

    mkdir -p ${DESTDIR}
    repo_folder="${DESTDIR}/usr/share/corellium/corellium-cli/"
    git checkout-index -a -f --prefix="$repo_folder"


    # BEGIN inside build folder
    pushd "$repo_folder"
      cli_version=$(jq .version --raw-output < package.json)
      corellium_cli_tarball="corellium-corellium-cli-$cli_version.tgz"

      node --version
      npm ci --unsafe-perm --ignore-scripts
      npm pack

      # Grab the packed tgz, move it up to a temporary file `tarred-ball`
      # and replace the contents of corellium-cli with the tarball so it's ok to distribute
      cp ${repo_folder}${corellium_cli_tarball} ${DESTDIR}/usr/share/corellium/tarred-ball
      rm -rf "$repo_folder"
      mkdir -p "$repo_folder"
      mv ${DESTDIR}/usr/share/corellium/tarred-ball "$repo_folder/$corellium_cli_tarball"
      ln -sf "${corellium_cli_tarball}" "${repo_folder}/corellium-cli-latest.tgz"

      # bundle together the built folder
      pushd $DESTDIR
      tar -czf ${OUTPUTDIR}/${PACKAGENAME}-build.tar.gz .
      popd

      rm -rf ${DESTDIR}

      # END inside build folder
    popd
}

build

rm -rf ${STAGINGDIR}
echo "Build for ${PACKAGENAME} completed"
