name: Build and Push to Harbor when new commit to main-branch

on:
  push:
    branches: [ main ]
  workflow_dispatch:

jobs:
  build:
    runs-on: linux_amd64
    steps:
      - uses: actions/checkout@v4

      - name: Login to Swissmakers Registry
        if: ${{ secrets.HARBOR_REGISTRY && secrets.HARBOR_USERNAME && secrets.HARBOR_PASSWORD }}
        env:
          REGISTRY: ${{ secrets.HARBOR_REGISTRY }}
          ROBOT_USER: ${{ secrets.HARBOR_USERNAME }}
          ROBOT_PASS: ${{ secrets.HARBOR_PASSWORD }}
        run: |
          mkdir -p "$HOME/.config/containers"
          echo "$ROBOT_PASS" | podman login --username "$ROBOT_USER" --password-stdin "$REGISTRY"

      - name: Build & tag for Swissmakers Registry
        env:
          REG:  ${{ secrets.HARBOR_REGISTRY }}
          PROJ: ${{ secrets.HARBOR_PROJECT }}
        run: |
          podman build -t $REG/$PROJ/fail2ban-ui:${{ github.sha }} .
          podman tag  $REG/$PROJ/fail2ban-ui:${{ github.sha }} $REG/$PROJ/fail2ban-ui:latest

      - name: Push to Swissmakers Registry
        env:
          REG:  ${{ secrets.HARBOR_REGISTRY }}
          PROJ: ${{ secrets.HARBOR_PROJECT }}
        run: |
          podman push $REG/$PROJ/fail2ban-ui:${{ github.sha }}
          podman push $REG/$PROJ/fail2ban-ui:latest

      - name: Login to Docker Hub
        if: ${{ secrets.DOCKERHUB_USERNAME && secrets.DOCKERHUB_TOKEN }}
        env:
          DH_USER: ${{ secrets.DOCKERHUB_USERNAME }}
          DH_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
        run: |
          echo "$DH_TOKEN" | podman login docker.io --username "$DH_USER" --password-stdin

      - name: Re-tag the build image for Docker Hub
        if: ${{ secrets.DOCKERHUB_USERNAME && secrets.DOCKERHUB_TOKEN }}
        env:
          REG:  ${{ secrets.HARBOR_REGISTRY }}
          PROJ: ${{ secrets.HARBOR_PROJECT }}
          DH_NS: ${{ secrets.DOCKERHUB_USERNAME }}
          DH_REPO: fail2ban-ui
        run: |
          podman tag $REG/$PROJ/fail2ban-ui:${{ github.sha }} docker.io/$DH_NS/$DH_REPO:${{ github.sha }}
          podman tag $REG/$PROJ/fail2ban-ui:${{ github.sha }} docker.io/$DH_NS/$DH_REPO:latest

      - name: Push to Docker Hub
        if: ${{ secrets.DOCKERHUB_USERNAME && secrets.DOCKERHUB_TOKEN }}
        env:
          DH_NS: ${{ secrets.DOCKERHUB_USERNAME }}
          DH_REPO: fail2ban-ui
        run: |
          podman push docker.io/$DH_NS/$DH_REPO:${{ github.sha }}
          podman push docker.io/$DH_NS/$DH_REPO:latest