#!/bin/bash

# Usage: ./preview.sh [public|private]
TARGET=$1

if [ "$TARGET" != "public" ] && [ "$TARGET" != "private" ]; then
    echo "Usage: $0 [public|private]"
    exit 1
fi

# Cleanup function to run when the script exits
cleanup() {
    echo -e "\n🧹 Cleaning up symlinks and restoring default framework configurations..."
    rm -rf content static config/_default/menus.en.toml
    
    # Restore the framework defaults from git checkout
    git checkout -- content static config/_default/menus.en.toml &>/dev/null
}

# Trap exits (Ctrl+C, kill signals, normal exit) and run cleanup
trap cleanup EXIT INT TERM

echo "🚀 Setting up symlinks for: $TARGET docs..."

# 1. Establish symlinks for content and static directories
rm -rf content static
ln -s /srv/docs/$TARGET content
ln -s /srv/docs/$TARGET/static static

# 2. Establish symlink for config override if it exists
if [ -f "/srv/docs/$TARGET/config/_default/menus.en.toml" ]; then
    rm -f config/_default/menus.en.toml
    ln -s /srv/docs/$TARGET/config/_default/menus.en.toml config/_default/menus.en.toml
fi

# 3. Start the dev server (blocks until stopped)
./run-dev.sh
