on:
  push:
    branches:
      - main

jobs:
  build-web:
    # custom runner image -> includes node and latest flutter stable
    runs-on: flutter-web-builder
    volumes:
      - /webpub:/webpub
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      # Cache pub dependencies (this should work now)
      - name: Cache pub dependencies
        uses: actions/cache@v4
        id: cache-pub
        with:
          path: /opt/pub-cache
          key: ${{ runner.os }}-pub-${{ hashFiles('**/pubspec.lock') }}
          restore-keys: |
            ${{ runner.os }}-pub-

      # Cache build outputs and tool cache
      - name: Cache Flutter build
        uses: actions/cache@v4
        with:
          path: |
            .dart_tool
            build
          key: ${{ runner.os }}-flutter-build-${{ hashFiles('**/pubspec.lock') }}-${{ hashFiles('lib/**/*.dart') }}
          restore-keys: |
            ${{ runner.os }}-flutter-build-${{ hashFiles('**/pubspec.lock') }}-
            ${{ runner.os }}-flutter-build-

      - name: Get dependencies
        run: flutter pub get

      - name: Build web
        run: flutter build web --wasm --release --base-href /shitman/
      
      - name: Empty webpub mount
        run: |
          if [ -d /webpub ]; then
            rm -rf /webpub/*
          else
            echo "No /webpub mount found, skipping empty."
          fi
      
      # if the /webpub mount exists, copy the build output there (with shitty temp hack)
      - name: Copy build output to /webpub
        run: |
          if [ -d /webpub ]; then
            cp -r build/web/* /webpub/
            cd /webpub
            ln -s . shitman
          else
            echo "No /webpub mount found, skipping copy."
          fi

      - name: List build output
        run: ls -la build/web/

      - name: Upload build artifacts
        uses: actions/upload-artifact@v3
        with:
          name: web-build
          path: build/web/
