#!/usr/bin/env bash

set -eu

echo "CDv3 CI"
echo `pwd`

# Check if this is a CI machine on Bamboo;
# if so, clone ssh keys so we can install submodules, and install AWS config.
echo "Checking if we need to copy ssh"
if [[ $(id --user --name) == root ]] && [[ "${ZOOX_PROJECT_NAME:-}" == coredashv3 ]]; then
  echo "Copying zoox's SSH credentials from '/home/zoox/.ssh' to '/root/.ssh'..."
  cp --recursive /home/zoox/.ssh /root/.ssh
  chmod 600 /root/.ssh/*
  echo "Copying zoox's AWS credentials from '/home/zoox/.aws' to '/root/.aws'..."
  cp --recursive /home/zoox/.aws /root/.aws
fi

source scripts/setup.sh

DRIVING_ROOT=$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../../../..)
SPECTRUM_ROOT=$DRIVING_ROOT/spectrum
COREDASH_ROOT=$SPECTRUM_ROOT/apps/coredash
LICENSE_CHECKER=$DRIVING_ROOT/spectrum/scripts/licenseChecker.py

# Now that dependent modules have been added, check their licenses
echo "Checking licensing of CoreDash dependencies"
cd $COREDASH_ROOT
$LICENSE_CHECKER licenses.config.js || exit 1

echo "Checking licensing of Spectrum 3D dependencies"
cd $SPECTRUM_ROOT/spectrum3d
$LICENSE_CHECKER licenses.config.js || exit 1

echo "Checking licensing of BOB.js dependencies"
cd $SPECTRUM_ROOT/bobjs
$LICENSE_CHECKER licenses.config.js || exit 1

echo "Checking licensing of tsprotos dependencies"
cd $SPECTRUM_ROOT/tsprotos
$LICENSE_CHECKER licenses.config.js || exit 1

echo "Checking licensing of three-zrn dependencies"
cd $DRIVING_ROOT/mapping/zrn/web_viewer/three_zrn/
$LICENSE_CHECKER licenses.config.js || exit 1

echo "Running spectrum3d unit-tests"
cd $SPECTRUM_ROOT/spectrum3d
yarn jest || exit 1

echo "Running BOB.js unit-tests"
cd $SPECTRUM_ROOT/bobjs
yarn jest || exit 1

cd $COREDASH_ROOT

# Update our build info, shown in app and used for naming on aws.
export GIT_SHA=`git rev-parse HEAD`
export BUILD_SOURCE="bamboo"

node scripts/updateBuildInfo.js > src/build-info.json

echo "Running CoreDash unit-tests"
yarn jest || exit 1

echo "Running Lint on CoreDash"
yarn lint || exit 1

# Make a production build and push to aws.
echo "Building CoreDash with sha $GIT_SHA and source $BUILD_SOURCE"
yarn release || exit 1

echo "===================================================="
echo "Done releasing CoreDash! Artifacts available on S3:"
echo "===================================================="
ls -la dist_electron/ || exit 1

if ls dist_electron/*.AppImage; then
  echo "Assertion passed: AppImage is in dist_electron output."
  exit 0
else
  echo "ERROR: Assertion failed! AppImage is NOT in dist_electron output."
  echo "Check console output above for errors in yarn release process."
  exit 1
fi
