name: Release Helm Chart and Carvel package

on:
  push:
    paths:
      # update this file to trigger helm chart release
      - 'helm/sealed-secrets/Chart.yaml'
    branches:
      - main

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3.1.0
        with:
          fetch-depth: 0

      - name: Configure Git
        run: |
          git config user.name "$GITHUB_ACTOR"
          git config user.email "$GITHUB_ACTOR@users.noreply.github.com"

      - name: Install Helm
        uses: azure/setup-helm@v3.4
        with:
          version: v3.4.2

      - name: Run chart-releaser
        uses: helm/chart-releaser-action@v1.4.1
        with:
          charts_dir: helm
        env:
          CR_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
          CR_RELEASE_NAME_TEMPLATE: "helm-v{{ .Version }}"

      - name: Install Carvel
        uses: carvel-dev/setup-action@v1.3.0
        with:
          only: kbld, imgpkg
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Install yq
        run: |
          mkdir -p ~/bin
          wget https://github.com/mikefarah/yq/releases/download/v4.30.8/yq_linux_amd64 -O ~/bin/yq
          chmod +x ~/bin/yq

      - name: Get chart version
        run: |
          export PATH=~/bin:$PATH
          echo "chart_version=$(yq .version < ./helm/sealed-secrets/Chart.yaml)" >> $GITHUB_ENV

      - name: Create imglock file
        working-directory: ./helm
        run: |
          mkdir -p .imgpkg
          kbld -f <(helm template sealed-secrets) --imgpkg-lock-output .imgpkg/images.yml

      - name: Push imgpkg bundle
        working-directory: ./helm
        env:
          IMGPKG_REGISTRY_HOSTNAME: ghcr.io
          IMGPKG_REGISTRY_USERNAME: ${{ github.actor }}
          IMGPKG_REGISTRY_PASSWORD: ${{ secrets.GITHUB_TOKEN }}
        run: |
          imgpkg push -b ghcr.io/${{ github.repository_owner }}/sealed-secrets-carvel:${{ env.chart_version }} -f . --json > output
          echo carvel_pkg=$(cat output | grep Pushed | cut -d "'" -f2 ) >> $GITHUB_ENV

      - name: Update package.yaml
        run: |
          yq -i '.spec.version = "${{ env.chart_version }}"' carvel/package.yaml
          yq -i '.metadata.name = "sealedsecrets.bitnami.com.${{ env.chart_version }}"' carvel/package.yaml
          yq -i '.spec.template.spec.fetch.0.imgpkgBundle.image = "${{ env.carvel_pkg }}"' carvel/package.yaml
          git checkout -B 'release-carvel-${{ env.chart_version }}'
          git add carvel/package.yaml
          git commit -sm 'Release carvel package ${{ env.chart_version }}'
          git push origin 'release-carvel-${{ env.chart_version }}'

      - name: Create PR
        run: gh pr create --fill --base main --repo $GITHUB_REPOSITORY
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
