#!/bin/bash

if [ "$1" = "dev" ]; then
  DEV=1
  shift
else
  DEV=0
fi

PROJECT=liquidity-party
REMOTE=git.dxod.org/dexorder/dexorder

if [ "$BUILD" != "1" ]; then
  if [ "$DEV" = "1" ]; then
    TAG="dev$(date +%Y%m%d%H%M%S)"
  else
    DIRTY="$( git status | grep "Changes " )"
    if [ "$DIRTY" != "" ]; then
        echo This project has uncommited changes: deployment aborted.
        exit 1
    fi
    TAG="$( git log --oneline | head -1 | cut -d ' ' -f 1 )"
  fi
  echo Deploying $TAG
else
  echo Building
fi

# Load secret env vars (including NEXT_PUBLIC_* vars baked into the static bundle)
if [ -f .env-secret ]; then
  set -a
  # shellcheck disable=SC1091
  source .env-secret
  set +a
fi

npm run build || exit 1

if [ "$BUILD" != "1" ]; then
  echo Deploying with tag $TAG
  docker buildx build --platform linux/amd64 --no-cache -f deploy/Dockerfile -t dexorder/$PROJECT:latest . || exit 1
  docker tag dexorder/$PROJECT:latest dexorder/$PROJECT:$TAG
  docker tag dexorder/$PROJECT:$TAG $REMOTE/$PROJECT:$TAG
  docker tag $REMOTE/$PROJECT:$TAG $REMOTE/$PROJECT:latest
  docker push $REMOTE/$PROJECT:$TAG
  YAML=$(sed "s#image: dexorder/$PROJECT*#image: $REMOTE/$PROJECT:$TAG#" deploy/liquidity-party.k8s.yaml)
  echo "$YAML" | kubectl apply -f - || echo "$YAML" "\nkubectl apply failed" && exit 1
  echo "$(date)" deployed $REMOTE/$PROJECT:$TAG
else
  echo "$(date)" built
fi
