name: Build and Deploy Nuxt

on:
  push:
    branches: [master]

jobs:
  build:
    runs-on: docker
  
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      
      - name: Install SSH client
        run: |
          apt-get update -y && apt-get install -y openssh-client

      - name: Setup SSH inside container
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519

          # Add the container host to known_hosts
          ssh-keyscan -H ${{ secrets.DEPLOY_HOST }} >> ~/.ssh/known_hosts

      - name: Log in to registry
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.aranroig.com -u "${{ secrets.REGISTRY_USER }}" --password-stdin

      - name: Clone blog entries
        run: |
          rm -Rf /tmp/blogs
          git clone http://git.aranroig.com/Syndria98/blogs /tmp/blogs --depth 1
          mkdir -p ./frontend/content && cp -r /tmp/blogs/content/. ./frontend/content/

      - name: Build frontend
        run: |
          docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/aranroig-frontend:latest ./frontend
          docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/aranroig-frontend:latest

      - name: Build backend
        run: |
          docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/aranroig-backend:latest ./backend
          docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/aranroig-backend:latest

      - name: Copy files
        run: |
          scp docker-compose.yml deploy@${{ secrets.DEPLOY_HOST}}:/var/www/app/
          scp nginx.conf deploy@${{ secrets.DEPLOY_HOST }}:/var/www/app/nginx.conf

      - name: Deploy
        run: |
          ssh deploy@${{ secrets.DEPLOY_HOST }} << 'EOF'
            echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.aranroig.com -u "${{ secrets.REGISTRY_USER }}" --password-stdin
            cd /var/www/app/
            docker-compose pull
            docker-compose up -d
          EOF

