when:
  event:
    - push

steps:
  - name: Build and push a container image
    image: gitea.badhouseplants.net/badhouseplants/container-builder:latest
    environment:
      REGISTRY_TOKEN:
        from_secret: GITEA_REGISTRY_TOKEN
    privileged: true
    commands:
      - build-container
    backend_options:
      kubernetes:
        resources:
          requests:
            memory: 500Mi
            cpu: 200m
          limits:
            memory: 500Mi
        securityContext:
          privileged: true
  - name: Push a helm chart
    image: docker.io/alpine/helm
    environment:
      REGISTRY_TOKEN:
        from_secret: GITEA_REGISTRY_TOKEN
      CHART_PATH: ./helm/softplayer-web
    privileged: true
    commands:
      - |-
        helm registry login gitea.badhouseplants.net \
          --password=$REGISTRY_TOKEN \
          --username=devops-bot \
      - export SHORT_SHA="$(git rev-parse --short HEAD)"
      - yq e -i '.version += "+" + env(SHORT_SHA)' "$CHART_PATH/Chart.yaml"
      - yq e -i ".appVersion = env(CI_COMMIT_SHA)" "$CHART_PATH/Chart.yaml"
      - helm dep build "$CHART_PATH"
      - helm package "$CHART_PATH" -d packages;
      - export REGISTRY=$(echo oci://gitea.badhouseplants.net/$CI_REPO/helm | tr '[:upper:]' '[:lower:]')
      - export CHART_NAME=$(helm show chart "$CHART_PATH" | yq .name)
      - export CHART_VERSION=$(helm show chart "$CHART_PATH" | yq .version)
      - |-
        if helm pull $REGISTRY/$CHART_NAME:$CHART_VERSION; then
          echo "Chart is found in the upstream: $CHART_NAME:$CHART_VERSION"
          exit 0;
        fi
        helm push "./packages/$CHART_NAME-$CHART_VERSION.tgz" "$REGISTRY"
