variables:
  INSTANCE: 'Writerside/in'
  ARTIFACT: 'webHelpIN2-all.zip'
  DOCKER_VERSION: '243.22562'
  ALGOLIA_APP_NAME: 'IH6YW1953U'
  ALGOLIA_INDEX_NAME: 'ZUSAMMENFASSUNGEN'
  CONFIG_JSON_PRODUCT: 'IN'
  CONFIG_JSON_VERSION: '1.0'

stages:
  - build
  - test
  - deploy
  - search

build:
    stage: build
    image: registry.jetbrains.team/p/writerside/builder/writerside-builder:$DOCKER_VERSION
    script:
      - set -e
      - export DISPLAY=:99
      - Xvfb :99 &
      - PROJECT_ID=$(echo $INSTANCE | cut -d'/' -f2 | tr '[:lower:]' '[:upper:]')
      - ARTIFACT="webHelp${PROJECT_ID}2-all.zip"
      - /opt/builder/bin/idea.sh helpbuilderinspect -source-dir . -product $INSTANCE --runner gitlab -output-dir public
      - echo "Testing existence of $ARTIFACT..."
      - ls -la public
      - test -e public/$ARTIFACT
    artifacts:
      paths:
        - public/$ARTIFACT
        - public/report.json
        - public/$ALGOLIA_ARTIFACT
      expire_in: 1 week

test:
  stage: test
  image: openjdk:18-jdk-alpine
  before_script:
    - apk add curl
  script:
    - cd public
    - curl -o wrs-checker.jar -L https://packages.jetbrains.team/maven/p/writerside/maven/com/jetbrains/writerside/writerside-ci-checker/1.0/writerside-ci-checker-1.0.jar
    - java -jar wrs-checker.jar report.json $INSTANCE
  dependencies:
    - build

pages:
  stage: deploy
  image: ubuntu:latest
  before_script:
    - apt-get update -y && apt-get install unzip -y

  script:
    - PROJECT_ID=$(echo $INSTANCE | cut -d'/' -f2 | tr '[:lower:]' '[:upper:]')
    - ARTIFACT="webHelp${PROJECT_ID}2-all.zip"
    - echo "Using artifact $ARTIFACT"
    - cd public
    - unzip -O UTF-8 $ARTIFACT
  dependencies:
    - build
  artifacts:
    paths:
      - public
    expire_in: 1 week

#search:
#  stage: search
#  image: registry.jetbrains.team/p/writerside/builder/algolia-publisher:2.0.32-3
#  dependencies:
#    - build
#    - test
#    - pages
#  script:
#    - echo "Checking contents of the public directory..."
#    - ls -la public
#    - if [ -z "$ALGOLIA_KEY" ]; then
#      echo "ALGOLIA_KEY is not set in Gitlab secrets";
#      exit 1;
#      fi
#    - echo "ALGOLIA_KEY is set"
#    - PROJECT_ID=$(echo $INSTANCE | cut -d'/' -f2 | tr '[:lower:]' '[:upper:]')
#    - ALGOLIA_ARTIFACT="algolia-indexes-${PROJECT_ID}.zip"
#    - echo "ALGOLIA_ARTIFACT is $ALGOLIA_ARTIFACT"
#    - if [ ! -f "public/$ALGOLIA_ARTIFACT" ]; then
#      echo "Artifacts file public/$ALGOLIA_ARTIFACT not found!";
#      exit 1;
#      fi
#    - unzip -O UTF-8 public/$ALGOLIA_ARTIFACT -d algolia-indexes
#    - env "algolia-key=$ALGOLIA_KEY" java -jar /opt/builder/help-publication-agent.jar update-index --application-name $ALGOLIA_APP_NAME --index-name $ALGOLIA_INDEX_NAME --product $CONFIG_JSON_PRODUCT --version $CONFIG_JSON_VERSION --index-directory algolia-indexes/ 2>&1 | tee algolia-update-index-log.txt
#  artifacts:
#    paths:
#      - algolia-update-index-log.txt
#    expire_in: 1 week