name: Build and Push Image

on:
  push:
    branches: ["**"]

env:
  DOCKER_TLS_CERTDIR: /certs
  IMAGE_TAG: ${{ github.sha }}
  SHORT_SHA: ${{ github.sha }}

jobs:
  spfn-website:
    runs-on: debian-trixie

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v7
        with:
          submodules: recursive

      - name: Cache Container Storage
        uses: actions/cache@v6
        with:
          path: |
            /var/lib/containers/storage
            /run/containers/storage
            ~/.local/share/containers/storage
          key: image-cache
      
      - name: Login to Registry
        run: $RNEX_CONTAINER_PLATFORM login -u ${{ secrets.PACKAGE_USER }} -p ${{ secrets.PACKAGE_PWD }} git.spbr.net

      - name: Set Short SHA
        run: echo "SHORT_SHA=${GITHUB_SHA::6}" >> $GITHUB_ENV
      
      - name: Build and Push
        env:
          CI_REGISTRY_IMAGE: git.spbr.net/spacebar/spfn-website
          CI_COMMIT_SHORT_SHA: ${{ env.SHORT_SHA }}
        run: |
          $RNEX_CONTAINER_PLATFORM login -u ${{ secrets.PACKAGE_USER }} -p ${{ secrets.PACKAGE_PWD }} git.spbr.net
          $RNEX_CONTAINER_PLATFORM build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" .
          $RNEX_CONTAINER_PLATFORM push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"

      - name: Push Retagged Latest
        if: github.ref == 'refs/heads/main'
        env:
          CI_REGISTRY_IMAGE: git.spbr.net/spacebar/spfn-website
          CI_COMMIT_SHORT_SHA: latest
          CI_COMMIT_PREVIOUS_SHA: ${{ env.SHORT_SHA }}
        run: |
          $RNEX_CONTAINER_PLATFORM login -u ${{ secrets.PACKAGE_USER }} -p ${{ secrets.PACKAGE_PWD }} git.spbr.net
          $RNEX_CONTAINER_PLATFORM pull "$CI_REGISTRY_IMAGE:$CI_COMMIT_PREVIOUS_SHA"
          $RNEX_CONTAINER_PLATFORM tag "$CI_REGISTRY_IMAGE:$CI_COMMIT_PREVIOUS_SHA" "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"
          $RNEX_CONTAINER_PLATFORM push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"
