name: Build and push docker image and deploy

on:
  push:
    branches:
      - main

jobs:
  build_and_push:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Log in to Github Container registry
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.DOCKER_REGISTRY_TOKEN }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v4
        with:
          context: .
          push: true
          tags: ghcr.io/${{ github.actor }}/skyjo-fe:latest

  deploy:
    needs: build_and_push
    if: ${{ success() }}
    runs-on: self-hosted
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Deploy to target server
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          echo "$DEPLOY_KEY" > deploy_key.pem
          chmod 600 deploy_key.pem
          scp -i deploy_key.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null .github/scripts/deploy.sh $DEPLOY_USER@$DEPLOY_HOST:/tmp/
          ssh -i deploy_key.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null $DEPLOY_USER@$DEPLOY_HOST "GITHUB_TOKEN=$GITHUB_TOKEN bash -s" < /tmp/deploy.sh
          rm -f deploy_key.pem
