name: docker-push
on:
  push:
    branches:
      - main
  workflow_dispatch:
jobs:
  build-and-push:
    runs-on: Nexus
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - name: Compute image and tags
        run: |
          IMG_NAME="${{ secrets.IMAGE_NAME }}"
          if [ -z "$IMG_NAME" ]; then IMG_NAME="nexus-material"; fi
          echo "IMAGE=${{ secrets.REGISTRY }}/${{ secrets.REGISTRY_NAMESPACE }}/$IMG_NAME" >> $GITHUB_ENV
          echo "SHA=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
      - uses: docker/login-action@v3
        with:
          registry: ${{ secrets.REGISTRY }}
          username: ${{ secrets.REGISTRY_USERNAME }}
          password: ${{ secrets.REGISTRY_PASSWORD }}
      - uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: |
            ${{ env.IMAGE }}:latest
            ${{ env.IMAGE }}:${{ env.SHA }}
  deploy:
    runs-on: Nexus
    needs: build-and-push
    steps:
      - uses: actions/checkout@v4
      - name: Set image ref
        run: |
          IMG_NAME="${{ secrets.IMAGE_NAME }}"
          if [ -z "$IMG_NAME" ]; then IMG_NAME="nexus-material"; fi
          echo "IMAGE_REF=${{ secrets.REGISTRY }}/${{ secrets.REGISTRY_NAMESPACE }}/$IMG_NAME:latest" >> $GITHUB_ENV
      - name: Upload compose to server
        uses: appleboy/scp-action@v0.1.7
        with:
          host: ${{ secrets.DEPLOY_HOST }}
          username: ${{ secrets.DEPLOY_USER }}
          password: ${{ secrets.DEPLOY_PASSWORD }}
          port: ${{ secrets.DEPLOY_PORT || 22 }}
          source: "docker-compose.yml"
          target: "~/nexus_mat"
      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.DEPLOY_HOST }}
          username: ${{ secrets.DEPLOY_USER }}
          password: ${{ secrets.DEPLOY_PASSWORD }}
          port: ${{ secrets.DEPLOY_PORT || 22 }}
          script: |
            set -e
            mkdir -p ~/nexus_mat
            cd ~/nexus_mat
            echo "IMAGE_REF=${{ env.IMAGE_REF }}" > .env.compose
            export IMAGE_REF=${{ env.IMAGE_REF }}
            docker login ${{ secrets.REGISTRY }} -u ${{ secrets.REGISTRY_USERNAME }} -p ${{ secrets.REGISTRY_PASSWORD }}
            docker compose pull
            docker compose up -d
