#!/bin/sh
set -e
# The "Sovereign Build" Hook (Hybrid Late-Stage Edition)

GIT_DIR="/home/mike/git/mikelev.in.git"
WORK_TREE="/home/mike/www/mikelev.in"

echo "🎯 [Hook] Received Push. Deploying..."

# 1. Force Checkout to the Web Root
git --work-tree=$WORK_TREE --git-dir=$GIT_DIR checkout -f main

# 2. Enter the Arena
cd $WORK_TREE
echo "🔨 [Hook] Starting Hybrid Build..."

# 3. The Build Command via Quoted Heredoc
# The single quotes around 'EOF' prevent the outer shell from expanding ANY variables.
nix develop .#quiet --command bash << 'EOF'
  echo '🏗️  Jekyll Build...'
  bundle exec jekyll build --future
  
  echo '📄 Publishing Source Markdown (Chisel-Strike)...'
  # 1. Faster Copy: Copy all source markdown to their permalink locations in _site
  # (Your existing loop to create directories and copy files remains here, 
  # but REMOVE the awk/python calls inside it).
  
  for post in _posts/*.md; do
    PERMALINK=$(grep -m 1 '^permalink:' "$post" | sed -e 's/^permalink:[[:space:]]*//' -e 's/["'\''[:space:]]//g')
    if [ -n "$PERMALINK" ]; then
      mkdir -p "_site$PERMALINK"
      cp "$post" "_site${PERMALINK}index.md"
      sed -i -e 's/{% raw %}//g' -e 's/{% endraw %}//g' "_site${PERMALINK}index.md"
    fi
  done

  # 2. Run the Batch Surgeon ONCE
  python3 /home/mike/www/mikelev.in/scripts/dye_injector_v2.py "/home/mike/www/mikelev.in/_site"
EOF

# --- NEW: Deploy the Map File ---
echo '🗺️  Deploying Nginx Redirect Map...'
cp _redirects.map _site/redirects.map
# --------------------------------

# 4. Permissions Fix
echo "🔒 [Hook] Fixing Permissions..."
chmod -R 755 $WORK_TREE/_site

echo "✅ [Hook] Deployment Complete. Site is Live."
