stages:
- build
- build docker
- manifest

.build: &build
  stage: build
  cache:
    paths:
    - .cache
  before_script:
  - mkdir -p .cache
  - export GOPATH="$CI_PROJECT_DIR/.cache"
  - export GOCACHE="$CI_PROJECT_DIR/.cache/build"
  - export GO_LDFLAGS="-linkmode external -extldflags -static -X main.Tag=$CI_COMMIT_TAG -X main.Commit=$CI_COMMIT_SHA -X 'main.BuildTime=`date '+%b %_d %Y, %H:%M:%S'`'"
  script:
  - go build -ldflags "$GO_LDFLAGS" -o mautrix-whatsapp
  artifacts:
    paths:
    - mautrix-whatsapp
    - example-config.yaml

.build-docker: &build-docker
  image: docker:stable
  stage: build docker
  before_script:
  - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  script:
  - docker pull $CI_REGISTRY_IMAGE:latest || true
  - docker build --pull --cache-from $CI_REGISTRY_IMAGE:latest --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-$DOCKER_ARCH . --file Dockerfile.ci
  - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-$DOCKER_ARCH
  - docker rmi $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-$DOCKER_ARCH

build amd64:
  <<: *build
  image: dock.mau.dev/tulir/gomuks-build-docker:linux-amd64

build arm64:
  <<: *build
  image: dock.mau.dev/tulir/gomuks-build-docker:linux-arm64

build arm:
  <<: *build
  image: dock.mau.dev/tulir/gomuks-build-docker:linux-arm

build docker amd64:
  <<: *build-docker
  tags:
  - amd64
  dependencies:
  - build amd64
  needs:
  - build amd64
  variables:
    DOCKER_ARCH: amd64
  after_script:
  - |
    if [ "$CI_COMMIT_BRANCH" = "master" ]; then
      apk add --update curl
      rm -rf /var/cache/apk/*
      curl "$NOVA_ADMIN_API_URL" -H "Content-Type: application/json" -d '{"password":"'"$NOVA_ADMIN_NIGHTLY_PASS"'","bridge":"'$NOVA_BRIDGE_TYPE'","image":"'$CI_REGISTRY_IMAGE':'$CI_COMMIT_SHA'-amd64"}'
    fi

build docker arm64:
  <<: *build-docker
  tags:
  - arm64
  dependencies:
  - build arm64
  needs:
  - build arm64
  variables:
    DOCKER_ARCH: arm64

manifest:
  stage: manifest
  variables:
    GIT_STRATEGY: none
  before_script:
  - "mkdir -p $HOME/.docker && echo '{\"experimental\": \"enabled\"}' > $HOME/.docker/config.json"
  - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  needs:
  - build docker amd64
  - build docker arm64
  script:
  - docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64
  - docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64
  - if [ "$CI_COMMIT_BRANCH" = "master" ]; then docker manifest create $CI_REGISTRY_IMAGE:latest $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64 $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64 && docker manifest push $CI_REGISTRY_IMAGE:latest; fi
  - if [ "$CI_COMMIT_BRANCH" != "master" ]; then docker manifest create $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64 $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64 && docker manifest push $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME; fi
  - docker rmi $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64 $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64