#!/bin/bash -e

ROOT=`dirname $0`

VERSION=""
DIST=""
RELEASE=""
NODE_ROOT="../../mobile/nodejs-assets/nodejs-project/"

"$ROOT"/copy-migrations
cd "$ROOT"

POSITIONAL=()
while [[ $# -gt 0 ]]; do
  key="$1"

  case $key in
      --version)
      VERSION="$2"
      shift
      shift
      ;;
      --dist)
      DIST="$2"
      shift
      shift
      ;;
      --beta)
      RELEASE="beta"
      shift
      ;;
      --release)
      RELEASE="production"
      shift
      ;;
      *)
      POSITIONAL+=("$1")
      shift
      ;;
  esac
done
set -- "${POSITIONAL[@]}"

if ([ -z "$VERSION" ] || [ -z "$DIST" ]) && [ -n "$RELEASE" ]; then
    echo "Version and dist are required if making a release"
    exit 1
fi

../node_modules/.bin/webpack --config ../webpack/webpack.mobile.config.js --progress

cp ../lib-dist/bundle.mobile.js "$NODE_ROOT/bundle.mobile.js"

SENTRY="../../mobile/node_modules/.bin/sentry-cli"

if [ -n "$RELEASE" ]; then
  git push origin master

  # Upload sourcemaps for mobile
  RELEASE_NAME="com.shiftreset.actual@$VERSION+$DIST"
  $SENTRY releases -o shift-reset-llc -p actual-mobile set-commits "$RELEASE_NAME" --auto

  $SENTRY releases -o shift-reset-llc -p actual-mobile files "$RELEASE_NAME" \
             delete app:///bundle.mobile.js

  $SENTRY releases -o shift-reset-llc -p actual-mobile files "$RELEASE_NAME" \
             delete app:///bundle.mobile.js.map

  $SENTRY releases -o shift-reset-llc -p actual-mobile files "$RELEASE_NAME" \
      upload-sourcemaps --no-rewrite \
      --dist "$DIST" --url-prefix 'app:///' ../lib-dist/bundle.mobile*
fi
