default:
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  interruptible: true

stages:
  - pre-build
  - build

variables:
    SECURE_FILES_DOWNLOAD_PATH: '.secure'

get-cookie:
  stage: pre-build
  image: ubuntu:jammy
  before_script:
    - apt-get update && apt-get upgrade -y && apt-get install curl jq -y
  script:
    - echo "Copying secure file with FeBio login ..."
    - curl --silent "https://gitlab.com/gitlab-org/incubation-engineering/mobile-devops/download-secure-files/-/raw/main/installer" | bash
    - export USERNAME=$(grep 'username:' ${SECURE_FILES_DOWNLOAD_PATH}/febio_login.txt | cut -d ':' -f2 | tr -d ' ')
    - export PASSWORD=$(grep 'password:' ${SECURE_FILES_DOWNLOAD_PATH}/febio_login.txt | cut -d ':' -f2 | tr -d ' ')
    - export ENCODED_USERNAME=$(printf '%s' "${USERNAME}" | jq -sRr @uri)
    - export ENCODED_PASSWORD=$(printf '%s' "${PASSWORD}" | jq -sRr @uri)
    - curl -c cookies.txt -X POST -d "log=${ENCODED_USERNAME}&pwd=${ENCODED_PASSWORD}&wp-submit=1" "https://febio.org/wp-login.php" -v
  artifacts:
    paths:
      - cookies.txt
    expire_in: 5 minutes

docker-build:
  stage: build
  image: docker:latest
  services:
    - docker:dind
  dependencies: 
    - get-cookie
  script:
    - docker pull $CI_REGISTRY_IMAGE:latest || true
    - docker build --build-arg BUILDKIT_INLINE_CACHE=1 --cache-from $CI_REGISTRY_IMAGE:latest --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA --tag $CI_REGISTRY_IMAGE:latest .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
    - docker push $CI_REGISTRY_IMAGE:latest
