name: Deploy to Server

on:
  push:
    branches:
      - deploy

jobs:
  deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 25

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


      - name: Copy files to server
        uses: appleboy/scp-action@v0.1.6
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SSH_USER }}
          password: ${{ secrets.SSH_PASSWORD }}
          source: "."
          target: "/root/hshop/"
          rm: true 

      - name: Deploy environment file
        uses: appleboy/ssh-action@v0.1.6
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SSH_USER }}
          password: ${{ secrets.SSH_PASSWORD }}
          script: |
            mkdir -p /root/hshop/backend/
            printf "%s" "${{ secrets.ENV_FILE_CONTENT }}" > /root/hshop/backend/.env.local

            mkdir -p /root/hshop/frontend/
            printf "%s" "${{ secrets.FRONTEND_ENV }}" > /root/hshop/frontend/.env


      - name: Build and start Docker containers
        uses: appleboy/ssh-action@v0.1.6
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SSH_USER }}
          password: ${{ secrets.SSH_PASSWORD }}
          script: |
            cd /root/hshop/ || { echo "ERROR: دایرکتوری پیدا نشد"; exit 1; }
            
            docker compose down --remove-orphans --timeout 10 
            
            docker compose up --build --detach || { echo "ERROR: ارور در بیلد"; exit 1; }

      - name: display active containers 
        uses: appleboy/ssh-action@v0.1.6
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SSH_USER }}
          password: ${{ secrets.SSH_PASSWORD }}
          script: |
            cd /root/hshop/ || { echo "ERROR: دایرکتوری پیدا نشد"; exit 1; }
            docker compose ps

      - name: clean up server
        uses: appleboy/ssh-action@v0.1.6
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SSH_USER }}
          password: ${{ secrets.SSH_PASSWORD }}
          script: |

            docker image prune -af --filter "until=48h" || { echo "ERROR: ارور در پاک کردن images";}

            docker builder prune -af --filter "until=48h" || { echo "ERROR: ارور در پاک کردن builder cache";}
