steps:
  - name: maven-build
    image: maven:3.9.16-eclipse-temurin-25
    when:
      event:
        - push
        - pull_request
        - manual
      branch:
        - master
        - develop
        - main
    environment:
      ACTIVE_APPS: &active_apps "gb32960-ingest-app jt808-ingest-app yutong-mqtt-app vehicle-history-app vehicle-analytics-app"
    commands: |
      cd $CI_WORKSPACE

      ACTIVE_MODULES=""
      for APP_NAME in $ACTIVE_APPS; do
        if [ -z "$ACTIVE_MODULES" ]; then
          ACTIVE_MODULES=":$APP_NAME"
        else
          ACTIVE_MODULES="$ACTIVE_MODULES,:$APP_NAME"
        fi
      done

      mvn -B -ntp -am -pl "$ACTIVE_MODULES" package -Dmaven.test.skip=true

      BRANCH_NAME=$(echo ${CI_COMMIT_BRANCH:-local} | tr / -)
      PROJECT_VERSION=$(mvn -q -DforceStdout help:evaluate -Dexpression=project.version)
      SHORT_SHA=$(echo ${CI_COMMIT_SHA:-manual} | cut -c1-8)
      IMAGE_VERSION="$BRANCH_NAME-$PROJECT_VERSION-$SHORT_SHA"

      echo "Project version: $PROJECT_VERSION"
      echo "Image version: $IMAGE_VERSION"
      echo "$IMAGE_VERSION" > $CI_WORKSPACE/project_version.txt

  - name: docker-build-apps
    image: docker:24.0.5-cli
    when:
      event:
        - push
        - pull_request
        - manual
      branch:
        - master
        - develop
        - main
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      ACTIVE_APPS: *active_apps
      ALIYUN_ACR_USERNAME:
        from_secret: aliyun_acr_username
      ALIYUN_ACR_PASSWORD:
        from_secret: aliyun_acr_password
    commands: |
      cd $CI_WORKSPACE
      APP_VERSION=$(cat $CI_WORKSPACE/project_version.txt)
      REGISTRY=${LINGNIU_IMAGE_REGISTRY:-crpi-85r4m0ackrm3qpje.cn-shanghai.personal.cr.aliyuncs.com}
      NAMESPACE=${LINGNIU_IMAGE_NAMESPACE:-oneos}

      printf '%s' "$ALIYUN_ACR_PASSWORD" | docker login \
        --username "$ALIYUN_ACR_USERNAME" \
        --password-stdin \
        "$REGISTRY"

      for APP_NAME in $ACTIVE_APPS; do
        IMAGE=$REGISTRY/$NAMESPACE/$APP_NAME:$APP_VERSION
        echo "Building and pushing $IMAGE"

        docker build \
          --build-arg APP_NAME=$APP_NAME \
          --build-arg APP_VERSION=$APP_VERSION \
          -t $IMAGE .

        docker push $IMAGE
      done
