stages:
  - build

variables:
  INTERNAL_REGISTRY: "10.10.10.10:9080"
  IMAGE_NAME: "$INTERNAL_REGISTRY/$CI_PROJECT_PATH"
  CI_SERVER_URL: "http://10.10.10.10:9080"
  GITLAB_FEATURES: ""

docker-build:
  stage: build
  image:
    name: gcr.io/kaniko-project/executor:v1.23.2-debug
    entrypoint: [""]
  rules:
    - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH
  before_script:
    - mkdir -p /kaniko/.docker
    - |
      cat > /kaniko/.docker/config.json <<EOF
      {
        "auths": {
          "$INTERNAL_REGISTRY": {
            "username": "$CI_REGISTRY_USER",
            "password": "$CI_REGISTRY_PASSWORD"
          }
        }
      }
      EOF
  script:
    - |
      if [ "$CI_COMMIT_REF_NAME" = "main" ]; then
        TAG="main"
        VERSION="1.0.0"
        CHANNEL="stable"
      elif [ "$CI_COMMIT_REF_NAME" = "feature/nightly" ] || [ "$CI_COMMIT_REF_NAME" = "nightly" ]; then
        TAG="nightly"
        VERSION="1.0.0-nightly"
        CHANNEL="nightly"
      else
        CLEAN_TAG=$(echo "$CI_COMMIT_REF_NAME" | sed 's/\//-/g')
        TAG="$CLEAN_TAG"
        VERSION="1.0.0-dev"
        CHANNEL="dev"
      fi

      DESTINATIONS="--destination=$IMAGE_NAME:$CI_COMMIT_SHA --destination=$IMAGE_NAME:$TAG"
      if [ "$CI_COMMIT_REF_NAME" = "main" ]; then
        DESTINATIONS="$DESTINATIONS --destination=$IMAGE_NAME:latest"
      fi

      echo "Building for channel $CHANNEL with version $VERSION and tag $TAG"
      echo "Using registry image: $IMAGE_NAME"

      /kaniko/executor \
        --context "$CI_PROJECT_DIR" \
        --dockerfile "$CI_PROJECT_DIR/Dockerfile" \
        --build-arg "VITE_BUILD_CHANNEL=$CHANNEL" \
        --build-arg "VITE_APP_VERSION=$VERSION" \
        --cache=true \
        --cache-repo="$IMAGE_NAME/cache" \
        --insecure-registry=$INTERNAL_REGISTRY \
        $DESTINATIONS
