#!/usr/bin/env bash

# exit on error
set -e

# https://docs.github.com/en/actions/publishing-packages/publishing-docker-images#publishing-images-to-github-packages

DIR="$(cd "$(dirname "$0")" && pwd)"
TAG=$1

if [[ -z "${GITHUB_USERNAME}" ]]; then
  echo "GITHUB_USERNAME env-var missing"
  exit 1
fi

if [[ -z "${GITHUB_TOKEN}" ]]; then
  echo "GITHUB_TOKEN env-var missing"
  exit 1
fi

if [ "$TAG" != "staging" ] && [ "$TAG" != "master" ]; then
  echo 'TAG argument ($1) should be "staging" or "master"'
fi

if [[ -z "${POEDITOR_API_TOKEN}" ]]; then
  echo 'POEDITOR_API_TOKEN env-var missing'
  exit 1
fi

if [[ -z "${GITHUB_NPM_TOKEN}" ]]; then
  echo 'GITHUB_NPM_TOKEN env-var missing'
  exit 1
fi

if [[ -z "${GIT_COMMIT}" ]]; then
  echo 'GIT_COMMIT env-var missing'
  exit 1
fi

cd $DIR

# login to the github container registry
echo $GITHUB_TOKEN | docker login ghcr.io -u $GITHUB_USERNAME --password-stdin

docker build \
  --no-cache \
  -t songwhip-api \
  --secret id=POEDITOR_API_TOKEN,env=POEDITOR_API_TOKEN \
  --secret id=GITHUB_NPM_TOKEN,env=GITHUB_NPM_TOKEN \
  --build-arg GIT_COMMIT=$GIT_COMMIT \
  ../../

# tag the built image as per github spec
# https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#tagging-container-images
docker tag songwhip-api ghcr.io/theorchard/songwhip-api:$TAG

# push the tagged image to github container registry
docker push ghcr.io/theorchard/songwhip-api:$TAG
