image: node:latest

stages:
  - test
  - publish
  - deploy

npm_test:
  stage: test
  script: 
    - PANDEMICS_DEPS=FALSE npm install

npmjs:
  stage: publish
  only:
    - tags
  script:
    # publish package to npmjs if possible
    - npm config set -- //registry.npmjs.org/:_authToken=\${NPM_TOKEN}
    - npx publish-if-not-exists

docker:
  stage: deploy
  only:
    - tags
  script:
    # trigger build pipeline of docker image
    - "curl -X POST --fail -F token=$CI_JOB_TOKEN -F ref=master https://gitlab.com/api/v4/projects/14637813/trigger/pipeline"

homebrew:
  image: homebrew/ubuntu22.04:latest
  stage: deploy
  only:
    - tags
  before_script:
    # check version on npmjs and brew
    - BREW_VERSION=`brew info pandemics --json | jq -r ".[0].versions.stable"`
    - NPMJS_VERSION=`curl https://registry.npmjs.org/pandemics/latest 2> /dev/null | jq -r ".version"`
    - git config --global user.email "${GITLAB_USER_EMAIL}"
    - git config --global user.name "${GITLAB_USER_NAME}"
  script:
    # if npm package is not more recent, exit
    - |
        if printf '%s\n' "$NPMJS_VERSION" "$BREW_VERSION" | sort -VC; then 
          echo "brew already up to date"
          exit 0
        fi
    # get new link and sha and do a pr
    - TARBALLURL=`curl https://registry.npmjs.org/pandemics/$NPMJS_VERSION 2> /dev/null | jq -r ".dist.tarball"`
    - curl $TARBALLURL --output "pandemics-${NPMJS_VERSION}.tar.gz"
    - brew bump-formula-pr pandemics --no-browse --url="${TARBALLURL}" --sha256="$(sha256sum pandemics-${NPMJS_VERSION}.tar.gz | cut -d ' ' -f 1)"