name: Deploy banu-front

on:
  push:
    branches: [master]
  workflow_dispatch:

jobs:
  deploy:
    runs-on: host
    env:
      IMAGE: banu-front
      CONTAINER: banu-front
      PORT: '8080'
      VITE_API_BASE_URL: ${{ vars.VITE_API_BASE_URL }}
      VITE_USE_MOCKS: ${{ vars.VITE_USE_MOCKS }}
    steps:
      - name: Clone repository at current commit
        run: |
          BUILD_DIR="$(mktemp -d -t banu-front-XXXXXX)"
          echo "BUILD_DIR=$BUILD_DIR" >> "$GITHUB_ENV"
          git clone http://109.122.252.86:3000/front-end/banu-front.git "$BUILD_DIR"
          git -C "$BUILD_DIR" checkout "${{ github.sha }}"

      - name: Build Docker image
        run: |
          docker build \
            --build-arg VITE_API_BASE_URL="$VITE_API_BASE_URL" \
            --build-arg VITE_USE_MOCKS="$VITE_USE_MOCKS" \
            -t "$IMAGE:${{ github.sha }}" \
            -t "$IMAGE:latest" \
            "$BUILD_DIR"

      - name: Replace running container
        run: |
          docker rm -f "$CONTAINER" 2>/dev/null || true
          docker run -d \
            --name "$CONTAINER" \
            --restart unless-stopped \
            -p "$PORT:80" \
            "$IMAGE:latest"

      - name: Prune dangling images
        run: docker image prune -f

      - name: Cleanup build dir
        if: always()
        run: rm -rf "$BUILD_DIR"

      - name: Show running container
        run: docker ps --filter "name=$CONTAINER" --format "table {{.Names}}\t{{.Image}}\t{{.Ports}}\t{{.Status}}"
