stages:
  - test
  - build
  - build-sonar

variables:
  GRADLE_USER_HOME: "$CI_PROJECT_DIR/.gradle"
  ANDROID_SDK_ROOT: "/opt/android-sdk"
  SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar"
  GIT_DEPTH: "0"

cache:
  key: "$CI_COMMIT_REF_SLUG"
  paths:
    - node_modules/
    - .gradle/

.before_android_job:
  image: mingc/android-build-box:latest
  before_script:
    - node --version
    - npm --version
    - npm ci
    - npx expo prebuild --platform android --non-interactive --no-install

build_apk_debug:
  extends: .before_android_job
  stage: build
  rules:
    - if: '$CI_COMMIT_BRANCH == "develop"'
  script:
    - cd android
    - ./gradlew assembleDebug
  artifacts:
    name: "apk-debug-$CI_COMMIT_SHORT_SHA"
    when: always
    expire_in: 7 days
    paths:
      - android/app/build/outputs/apk/debug/*.apk

build_aab_release_signed:
  extends: .before_android_job
  stage: build
  rules:
    - if: '$CI_COMMIT_TAG'
  script:
    - test -n "$ANDROID_KEYSTORE_BASE64"
    - test -n "$ANDROID_KEYSTORE_PASSWORD"
    - test -n "$ANDROID_KEY_ALIAS"
    - test -n "$ANDROID_KEY_PASSWORD"
    - echo "$ANDROID_KEYSTORE_BASE64" | base64 -d > android/release.keystore
    - cd android
    - |
      ./gradlew bundleRelease \
        -Pandroid.injected.signing.store.file="$CI_PROJECT_DIR/android/release.keystore" \
        -Pandroid.injected.signing.store.password="$ANDROID_KEYSTORE_PASSWORD" \
        -Pandroid.injected.signing.key.alias="$ANDROID_KEY_ALIAS" \
        -Pandroid.injected.signing.key.password="$ANDROID_KEY_PASSWORD"
  artifacts:
    name: "aab-release-$CI_COMMIT_TAG"
    when: always
    expire_in: 30 days
    paths:
      - android/app/build/outputs/bundle/release/*.aab

jest:
  stage: test
  image: node:20
  script:
    - npm ci
    - npm run test:coverage -- --ci
  artifacts:
    when: always
    expire_in: 1 day
    paths:
      - coverage/
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
    - if: $CI_COMMIT_BRANCH == 'master'
    - if: $CI_COMMIT_BRANCH == 'main'
    - if: $CI_COMMIT_BRANCH == 'develop'

build-sonar:
  stage: build-sonar
  image:
    name: sonarsource/sonar-scanner-cli:11
    entrypoint: [""]
  needs:
    - job: jest
      artifacts: true
  cache:
    policy: pull-push
    key: "sonar-cache-$CI_COMMIT_REF_SLUG"
    paths:
      - "${SONAR_USER_HOME}/cache"
      - sonar-scanner/
  script:
    - sonar-scanner -Dsonar.host.url="${SONAR_HOST_URL}"
  allow_failure: true
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
    - if: $CI_COMMIT_BRANCH == 'master'
    - if: $CI_COMMIT_BRANCH == 'main'
    - if: $CI_COMMIT_BRANCH == 'develop'
