# This file is a template, and might need editing before it works on your project.
# You can copy and paste this template into a new `.gitlab-ci.yml` file.
# You should not add this template to an existing `.gitlab-ci.yml` file by using the `include:` keyword.
#
# To contribute improvements to CI/CD templates, please follow the Development guide at:
# https://docs.gitlab.com/ee/development/cicd/templates.html
# This specific template is located at:
# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Nodejs.gitlab-ci.yml

# Official framework image. Look for the different tagged releases at:
# https://hub.docker.com/r/library/node/tags/

stages:
  - build
  - deploy

testCommit:
  stage: build
  image: node:latest
  # Pick zero or more services to be used on all builds.
  # Only needed when using a docker container to run your tests in.
  # Check out: https://docs.gitlab.com/ee/ci/services/index.html
  services:
    - postgres:15
    - redis
  variables:
    POSTGRES_PASSWORD: test
    # POSTGRES_DB: $POSTGRES_DB
    # POSTGRES_USER: $POSTGRES_USER
    # POSTGRES_PASSWORD: $POSTGRES_PASSWORD
    # POSTGRES_HOST_AUTH_METHOD: trust
  script:
    - apt-get update && apt-get install -y git wget curl build-essential python3 musl
    - curl https://sh.rustup.rs -sSf | sh -s -- -y
    - source "$HOME/.cargo/env"
    - ln -s /lib/x86_64-linux-musl/libc.so /lib/libc.musl-x86_64.so.1
    - cp .config/ci.yml .config/default.yml
    - corepack enable
    - corepack prepare pnpm@latest --activate
    - pnpm i --frozen-lockfile
    - pnpm run build:debug
    - pnpm run migrate
  cache:
    key: build
    policy: pull-push
    when: on_success
    paths:
     - node_modules/
     - packages/*/node_modules/
     - packages/backend/native-utils/node_modules/
  only:
    - main
    - beta
    - develop
    - /^feature\/.*$/

getImageTag:
  stage: deploy
  image: busybox
  script:
    - |
      if test -n "$CI_COMMIT_TAG"; then
        tag="$CI_COMMIT_TAG"
      elif test "$CI_COMMIT_BRANCH" == "main"; then
        tag="latest"
      else
        tag="$CI_COMMIT_BRANCH"
      fi
    - echo "REGISTRY_PUSH_TAG=$tag" | tee build.env
  # parse tag to the build and merge jobs.
  # See: https://docs.gitlab.com/ee/ci/variables/#pass-an-environment-variable-to-another-job
  artifacts:
    reports:
      dotenv: build.env
  only:
    - main
    - beta
    - tags

dockerBuild:
  stage: deploy
  needs: ["getImageTag"]
  image:
    name: gcr.io/kaniko-project/executor:debug
    entrypoint: [""]
  script:
    - /kaniko/executor
      --context "${CI_PROJECT_DIR}"
      --dockerfile "${CI_PROJECT_DIR}/Dockerfile"
      --destination "${CI_REGISTRY_IMAGE}:${REGISTRY_PUSH_TAG}"
  only:
    - main
    - beta
    - tags