#!/bin/bash

# DokuWiki Synchronization Script
# Syncs organized repository documentation to DokuWiki format

set -e

# Configuration
DOKUWIKI_HOST="atlantis.vish.local"
DOKUWIKI_PATH="/opt/dokuwiki/data/pages/homelab"
DOCS_DIR="docs"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${BLUE}📚 Syncing organized documentation to DokuWiki...${NC}"

# Function to convert markdown to DokuWiki format
convert_md_to_dokuwiki() {
    local input_file="$1"
    local output_file="$2"

    # Basic markdown to DokuWiki conversion
    sed -e 's/^# /====== /g' \
        -e 's/^## /===== /g' \
        -e 's/^### /==== /g' \
        -e 's/^#### /=== /g' \
        -e 's/^##### /== /g' \
        -e 's/^###### /= /g' \
        -e 's/====== \(.*\)/====== \1 ======/g' \
        -e 's/===== \(.*\)/===== \1 =====/g' \
        -e 's/==== \(.*\)/==== \1 ====/g' \
        -e 's/=== \(.*\)/=== \1 ===/g' \
        -e 's/== \(.*\)/== \1 ==/g' \
        -e 's/= \(.*\)/= \1 =/g' \
        -e 's/\*\*\([^*]*\)\*\*/\*\*\1\*\*/g' \
        -e 's/\*\([^*]*\)\*/\/\/\1\/\//g' \
        -e 's/`\([^`]*\)`/%%\1%%/g' \
        -e 's/```\([^`]*\)```/<code>\n\1\n<\/code>/g' \
        -e 's/^\* /  \* /g' \
        -e 's/^- /  \* /g' \
        -e 's/^\([0-9]\+\)\. /  - /g' \
        "$input_file" > "$output_file"
}

# Create local DokuWiki structure
echo -e "${BLUE}📁 Creating local DokuWiki structure...${NC}"
mkdir -p /tmp/dokuwiki_sync/homelab

# Create main start page
cat > /tmp/dokuwiki_sync/homelab/start.txt << 'EOF'
====== Homelab Documentation ======

===== Organized Documentation Structure =====

==== 🔧 Administration ====
  * [[homelab:admin:start|Administration Overview]]
  * [[homelab:admin:gitops_guide|GitOps Deployment Guide]]
  * [[homelab:admin:deployment_guide|Deployment Documentation]]
  * [[homelab:admin:operational_status|Operational Status]]
  * [[homelab:admin:development|Development Guide]]

==== 🏗️ Infrastructure ====
  * [[homelab:infrastructure:start|Infrastructure Overview]]
  * [[homelab:infrastructure:ssh_guide|SSH Access Guide]]
  * [[homelab:infrastructure:networking|Networking Guide]]
  * [[homelab:infrastructure:monitoring|Monitoring Setup]]

==== 🎯 Services ====
  * [[homelab:services:start|Services Overview]]
  * [[homelab:services:service_index|Service Index]]
  * [[homelab:services:dashboard_setup|Dashboard Setup]]
  * [[homelab:services:arr_suite|ARR Suite]]

==== 🚀 Getting Started ====
  * [[homelab:getting-started:start|Getting Started Overview]]
  * [[homelab:getting-started:quickstart|Beginner Quickstart]]
  * [[homelab:getting-started:what_is_homelab|What Is Homelab]]
  * [[homelab:getting-started:prerequisites|Prerequisites]]

==== 🛠️ Troubleshooting ====
  * [[homelab:troubleshooting:start|Troubleshooting Overview]]
  * [[homelab:troubleshooting:common_issues|Common Issues]]
  * [[homelab:troubleshooting:emergency_guide|Emergency Guide]]
  * [[homelab:troubleshooting:disaster_recovery|Disaster Recovery]]

==== 🔬 Advanced ====
  * [[homelab:advanced:start|Advanced Topics]]
  * [[homelab:advanced:optimization|Optimization Guide]]
  * [[homelab:advanced:scaling|Scaling Strategies]]

===== System Information =====

**Repository**: https://git.vish.gg/Vish/homelab
**Wiki**: https://git.vish.gg/Vish/homelab/wiki
**DokuWiki**: http://atlantis.vish.local:8399/doku.php?id=homelab:start

Last updated: [[date]]
EOF

# Process each docs subdirectory
echo -e "${BLUE}📄 Processing documentation files...${NC}"

processed_count=0

# Process admin docs
if [[ -d "$DOCS_DIR/admin" ]]; then
    mkdir -p /tmp/dokuwiki_sync/homelab/admin

    # Create admin start page
    cat > /tmp/dokuwiki_sync/homelab/admin/start.txt << 'EOF'
====== Administration ======

===== System Management & Operations =====

==== Core Administration ====
  * [[homelab:admin:gitops_guide|GitOps Deployment Guide]] - Complete deployment procedures
  * [[homelab:admin:deployment_guide|Deployment Documentation]] - Step-by-step deployment
  * [[homelab:admin:operational_status|Operational Status]] - Current system status
  * [[homelab:admin:development|Development Guide]] - Development procedures

==== Documentation & Integration ====
  * [[homelab:admin:agents|Agent Memory]] - AI agent context
  * [[homelab:admin:dokuwiki_integration|DokuWiki Integration]] - External wiki setup
  * [[homelab:admin:gitea_wiki_integration|Gitea Wiki Integration]] - Native wiki setup

[[homelab:start|← Back to Home]]
EOF

    # Convert admin markdown files
    for file in "$DOCS_DIR/admin"/*.md; do
        if [[ -f "$file" ]]; then
            filename=$(basename "$file" .md)
            dokuwiki_name=$(echo "$filename" | tr '[:upper:]' '[:lower:]' | sed 's/_/-/g')
            convert_md_to_dokuwiki "$file" "/tmp/dokuwiki_sync/homelab/admin/${dokuwiki_name}.txt"
            ((processed_count++))
            echo -e "${GREEN}✅ Converted: admin/$filename${NC}"
        fi
    done
fi

# Process infrastructure docs
if [[ -d "$DOCS_DIR/infrastructure" ]]; then
    mkdir -p /tmp/dokuwiki_sync/homelab/infrastructure

    cat > /tmp/dokuwiki_sync/homelab/infrastructure/start.txt << 'EOF'
====== Infrastructure ======

===== Core Infrastructure & Networking =====

==== Infrastructure Management ====
  * [[homelab:infrastructure:overview|Infrastructure Overview]] - Complete infrastructure guide
  * [[homelab:infrastructure:ssh_guide|SSH Access Guide]] - SSH access procedures
  * [[homelab:infrastructure:networking|Networking Guide]] - Network configuration
  * [[homelab:infrastructure:monitoring|Monitoring Setup]] - Monitoring configuration

[[homelab:start|← Back to Home]]
EOF

    for file in "$DOCS_DIR/infrastructure"/*.md; do
        if [[ -f "$file" ]]; then
            filename=$(basename "$file" .md)
            dokuwiki_name=$(echo "$filename" | tr '[:upper:]' '[:lower:]' | sed 's/_/-/g')
            convert_md_to_dokuwiki "$file" "/tmp/dokuwiki_sync/homelab/infrastructure/${dokuwiki_name}.txt"
            ((processed_count++))
            echo -e "${GREEN}✅ Converted: infrastructure/$filename${NC}"
        fi
    done
fi

# Process services docs
if [[ -d "$DOCS_DIR/services" ]]; then
    mkdir -p /tmp/dokuwiki_sync/homelab/services

    cat > /tmp/dokuwiki_sync/homelab/services/start.txt << 'EOF'
====== Services ======

===== Application Services & Setup =====

==== Service Management ====
  * [[homelab:services:service_index|Service Index]] - All available services
  * [[homelab:services:dashboard_setup|Dashboard Setup]] - Dashboard configuration
  * [[homelab:services:arr_suite|ARR Suite]] - Media services

[[homelab:start|← Back to Home]]
EOF

    for file in "$DOCS_DIR/services"/*.md; do
        if [[ -f "$file" ]]; then
            filename=$(basename "$file" .md)
            dokuwiki_name=$(echo "$filename" | tr '[:upper:]' '[:lower:]' | sed 's/_/-/g')
            convert_md_to_dokuwiki "$file" "/tmp/dokuwiki_sync/homelab/services/${dokuwiki_name}.txt"
            ((processed_count++))
            echo -e "${GREEN}✅ Converted: services/$filename${NC}"
        fi
    done
fi

# Process other directories similarly...
for dir in getting-started troubleshooting security hardware advanced runbooks; do
    if [[ -d "$DOCS_DIR/$dir" ]]; then
        mkdir -p "/tmp/dokuwiki_sync/homelab/$dir"

        for file in "$DOCS_DIR/$dir"/*.md; do
            if [[ -f "$file" ]]; then
                filename=$(basename "$file" .md)
                dokuwiki_name=$(echo "$filename" | tr '[:upper:]' '[:lower:]' | sed 's/_/-/g')
                convert_md_to_dokuwiki "$file" "/tmp/dokuwiki_sync/homelab/$dir/${dokuwiki_name}.txt"
                ((processed_count++))
                echo -e "${GREEN}✅ Converted: $dir/$filename${NC}"
            fi
        done
    fi
done

echo ""
echo -e "${BLUE}📊 DokuWiki Sync Summary:${NC}"
echo -e "${GREEN}✅ Files processed: $processed_count${NC}"
echo -e "${GREEN}📁 Structure created in: /tmp/dokuwiki_sync/homelab/${NC}"

echo ""
echo -e "${BLUE}📋 To complete DokuWiki sync, run on Atlantis server:${NC}"
echo -e "${YELLOW}# Copy the structure to DokuWiki${NC}"
echo -e "${YELLOW}sudo rsync -av /tmp/dokuwiki_sync/homelab/ $DOKUWIKI_PATH/${NC}"
echo -e "${YELLOW}sudo chown -R www-data:www-data $DOKUWIKI_PATH${NC}"
echo -e "${YELLOW}sudo chmod -R 755 $DOKUWIKI_PATH${NC}"

echo ""
echo -e "${GREEN}🌐 DokuWiki will be available at:${NC}"
echo -e "   ${BLUE}http://atlantis.vish.local:8399/doku.php?id=homelab:start${NC}"

echo ""
echo -e "${GREEN}✅ DokuWiki sync preparation completed!${NC}"
