name: Master Build

on:
  push:
    branches: [ "main" ]

jobs:
  build_amd64:
    name: Build and Push Docker Image (amd64)
    runs-on: self-hosted-ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Install docker and docker compose
        run: |
          apt update
          apt install -y docker docker-compose

      - name: Set up Docker Buildx
        id: buildx
        uses: docker/setup-buildx-action@v2
        with:
        config-inline: |
          [registry."git.ivanch.me"]

      - name: Login to Docker Hub
        uses: https://github.com/docker/login-action@v3.3.0
        with:
          registry: git.ivanch.me
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_ACCESS_TOKEN }}

      - name: Build Docker image and push
        id: docker_build
        uses: https://github.com/docker/build-push-action@v6.12.0
        with:
          context: ./
          file: ./Dockerfile
          push: true
          tags: git.ivanch.me/ivanch/new-home/home-page:latest
          platforms: linux/amd64

      - name: Image digest
        run: echo ${{ steps.docker_build.outputs.digest }}

  deploy:
    name: Update running container
    runs-on: self-hosted-ubuntu-latest
    needs: build_amd64

    steps:
    - name: Recreate container
      uses: https://github.com/appleboy/ssh-action@v1.2.0
      with:
        host: ${{ secrets.HOST }}
        username: ${{ secrets.USERNAME }}
        key: ${{ secrets.KEY }}
        port: ${{ secrets.PORT }}
        script: |
          cd ${{ secrets.PROJECT_DIR }}
          docker compose down
          docker compose rm
          docker compose pull
          docker compose up -d