name: Documentation

on:
  workflow_dispatch:
  push:
    branches: [ main ]
  pull_request:

concurrency:
  group: "docs"
  cancel-in-progress: false

env:
  GO_VERSION: '1.25.0'
  HUGO_VERSION: ${{ vars.HUGO_VERSION || '0.146.0' }}
  FORGEJO_PAGES_BRANCH: ${{ vars.FORGEJO_PAGES_BRANCH || 'pages' }}
  FORGEJO_DOCS_BASE_URL: ${{ vars.FORGEJO_DOCS_BASE_URL || '/' }}
  GH_PAGES_REPO: ${{ vars.GH_PAGES_REPO || '' }}
  GH_PAGES_BRANCH: ${{ vars.GH_PAGES_BRANCH || 'gh-pages' }}
  GH_DOCS_BASE_URL: ${{ vars.GH_DOCS_BASE_URL || '' }}

jobs:
  build-and-publish:
    runs-on: self-hosted
    steps:
    - name: Checkout
      uses: actions/checkout@v5

    - name: Install system dependencies
      run: |
        sudo apt-get update
        sudo apt-get install -y wget rsync git

    - name: Set up Go (for Hugo Modules)
      run: |
        REQUIRED_GO="${GO_VERSION}"
        if command -v go &> /dev/null && go version | grep -q "go${REQUIRED_GO}"; then
          echo "Go ${REQUIRED_GO} already installed - skipping download"
        else
          echo "Installing Go ${REQUIRED_GO}..."
          curl -sL "https://go.dev/dl/go${REQUIRED_GO}.linux-amd64.tar.gz" | sudo tar -C /usr/local -xzf -
          export PATH="/usr/local/go/bin:$PATH"
          echo "/usr/local/go/bin" >> $GITHUB_PATH
          echo "Go ${REQUIRED_GO} installed"
        fi
        go version

    - name: Install Hugo
      run: |
        echo "Target Hugo version: ${HUGO_VERSION}"
        
        # Remove ALL existing Hugo installations aggressively
        sudo apt-get remove -y hugo 2>/dev/null || true
        sudo rm -f /usr/bin/hugo /usr/local/bin/hugo /usr/local/go/bin/hugo 2>/dev/null || true
        sudo rm -rf /usr/local/hugo* 2>/dev/null || true
        
        # Download and install Hugo extended
        wget -q -O /tmp/hugo.deb "https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb"
        sudo dpkg -i /tmp/hugo.deb || sudo apt-get install -f -y
        
        # Find where hugo was installed
        HUGO_PATH=$(which hugo || echo "")
        if [ -z "$HUGO_PATH" ]; then
          # Check common locations
          for path in /usr/bin/hugo /usr/local/bin/hugo /opt/hugo/bin/hugo; do
            if [ -f "$path" ]; then
              HUGO_PATH="$path"
              break
            fi
          done
        fi
        
        if [ -z "$HUGO_PATH" ]; then
          echo "ERROR: Hugo not found after installation" >&2
          exit 1
        fi
        
        # Create symlink to standard location if needed
        if [ "$HUGO_PATH" != "/usr/bin/hugo" ]; then
          sudo ln -sf "$HUGO_PATH" /usr/bin/hugo
        fi
        
        # Verify the installed version
        echo ""
        echo "Installed Hugo version:"
        /usr/bin/hugo version
        
        # Export PATH to ensure correct Hugo is used
        echo "/usr/bin" >> $GITHUB_PATH

    - name: Build docs (Forgejo)
      run: |
        /usr/bin/hugo --source docs --gc --minify --baseURL "${FORGEJO_DOCS_BASE_URL}" --destination "${{ runner.temp }}/site-forgejo"
        /usr/bin/hugo version

    - name: Build docs (GitHub)
      if: env.GH_PAGES_REPO != ''
      run: |
        BASE_URL="${GH_DOCS_BASE_URL}"
        if [ -z "${BASE_URL}" ]; then
          BASE_URL="https://${GH_PAGES_REPO%%/*}.github.io/${GH_PAGES_REPO#*/}/"
        fi
        hugo --source docs --gc --minify --baseURL "${BASE_URL}" --destination "${{ runner.temp }}/site-github"

    - name: Upload build artifact
      uses: actions/upload-artifact@v4
      with:
        name: docs-site
        path: ${{ runner.temp }}/site-forgejo
        retention-days: 30

    - name: Publish docs to Forgejo
      if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
      env:
        FORGEJO_TOKEN: ${{ secrets.FORGEJO_PAGES_TOKEN || secrets.GITEA_TOKEN || secrets.GITHUB_TOKEN }}
      run: |
        if [ -z "${FORGEJO_TOKEN}" ]; then
          echo "Missing FORGEJO_PAGES_TOKEN (or GITEA_TOKEN/GITHUB_TOKEN fallback)" >&2
          exit 1
        fi

        SERVER_URL="${{ github.server_url }}"
        HOST="${SERVER_URL#https://}"
        HOST="${HOST#http://}"
        REMOTE="https://oauth2:${FORGEJO_TOKEN}@${HOST}/${{ github.repository }}.git"

        mkdir -p "${{ runner.temp }}/publish-forgejo"
        cd "${{ runner.temp }}/publish-forgejo"
        git init
        git checkout --orphan "${FORGEJO_PAGES_BRANCH}"
        rsync -a --delete "${{ runner.temp }}/site-forgejo/" ./
        git add -A
        git config user.name "forgejo-actions"
        git config user.email "actions@${HOST}"
        git commit -m "docs: publish" || true
        git remote add origin "${REMOTE}"
        git push --force origin "${FORGEJO_PAGES_BRANCH}"

    - name: Publish docs to GitHub Pages
      if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && env.GH_PAGES_REPO != ''
      env:
        GH_TOKEN: ${{ secrets.GH_PAGES_TOKEN || secrets.GH_MIRROR_TOKEN }}
      run: |
        if [ -z "${GH_TOKEN}" ]; then
          echo "Missing GH_PAGES_TOKEN (or GH_MIRROR_TOKEN fallback)" >&2
          exit 1
        fi

        REMOTE="https://x-access-token:${GH_TOKEN}@github.com/${GH_PAGES_REPO}.git"

        mkdir -p "${{ runner.temp }}/publish-github"
        cd "${{ runner.temp }}/publish-github"
        git init
        git checkout --orphan "${GH_PAGES_BRANCH}"
        rsync -a --delete "${{ runner.temp }}/site-github/" ./
        git add -A
        git config user.name "github-actions"
        git config user.email "actions@github.com"
        git commit -m "docs: publish" || true
        git remote add origin "${REMOTE}"
        git push --force origin "${GH_PAGES_BRANCH}"
