name: Build and Deploy Nuxt

on:
  push:
    branches: [master]

jobs:
  frontend:
    runs-on: docker

    container:
      image: node:20

    defaults:
      run:
        working-directory: ./aranroig

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install SSH client
        run: |
          apt-get update && 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: Install deps
        run: npm i

      - name: Build
        run: npm run build

      - name: Compress build
        run: tar -czf build.tar.gz .output

      - name: Deploy frontend to server
        run: |
          scp build.tar.gz deploy@${{ secrets.DEPLOY_HOST }}:/tmp/
          ssh deploy@${{ secrets.DEPLOY_HOST }} << 'EOF'
            rm -rf /var/www/app/.output
            tar -xzf /tmp/build.tar.gz -C /var/www/app
          EOF

  backend:
    runs-on: docker
    container:
      image: node:20
    defaults:
      run:
        working-directory: ./
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install SSH client
        run: |
          apt-get update && 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: Compress backend
        run: tar -czf backend.tar.gz backend

      - name: Send backend to server
        run: scp backend.tar.gz deploy@${{ secrets.DEPLOY_HOST }}:/tmp/

      - name: Unpack backend
        run: |
          ssh deploy@${{ secrets.DEPLOY_HOST }} << 'EOF'
            rm -rf /var/www/app/backend
            tar -xzf /tmp/backend.tar.gz -C /var/www/app
          EOF

      - name: Install dependencies on server
        run: |
          ssh deploy@${{ secrets.DEPLOY_HOST }} << 'EOF'
            cd /var/www/app/backend/ && npm i
          EOF


  deploy:
    runs-on: docker
    container:
      image: node:20
    needs: [frontend, backend]
    steps:
      - name: Copy ecosystem file
        run: scp ecosystem.config.js deploy@${{ secrets.DEPLOY_HOST }}:/var/www/app/
      - name: Restart server
        run: |
          ssh deploy@${{ secrets.DEPLOY_HOST }} << 'EOF'
            sudo systemctl restart app
          EOF

