#!/bin/bash

# Quick fix for Meilisearch service issues
# Fixes: NAMESPACE error and database version mismatch

set -e

echo "=========================================="
echo "Meilisearch Service Fix"
echo "=========================================="
echo ""

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}Please run as root or with sudo${NC}"
    exit 1
fi

# Step 1: Stop the service
echo -e "${YELLOW}Step 1: Stopping Meilisearch service...${NC}"
systemctl stop meilisearch 2>/dev/null || true
echo -e "${GREEN}Service stopped${NC}"

# Step 2: Fix database issue - ALWAYS clear database to fix version mismatch
echo ""
echo -e "${YELLOW}Step 2: Checking and clearing database...${NC}"
DATA_DIR="/var/lib/meilisearch"

# Always backup and clear to fix version mismatch
if [ -d "$DATA_DIR" ]; then
    # List what's there
    echo -e "${YELLOW}Current database contents:${NC}"
    ls -la "$DATA_DIR" 2>/dev/null || echo "Directory is empty or doesn't exist"
    echo ""
    
    # Check if there are any files
    if [ "$(ls -A $DATA_DIR 2>/dev/null)" ]; then
        echo -e "${YELLOW}Database files found. Creating backup...${NC}"
        BACKUP_DIR="/var/lib/meilisearch-backup-$(date +%Y%m%d-%H%M%S)"
        mkdir -p "$BACKUP_DIR"
        
        # Backup everything
        cp -a "$DATA_DIR"/. "$BACKUP_DIR/" 2>/dev/null || true
        echo -e "${GREEN}Backup created at: $BACKUP_DIR${NC}"
    fi
    
    # ALWAYS clear database to fix version mismatch error
    echo -e "${YELLOW}Clearing database to fix version mismatch...${NC}"
    # Stop service first to ensure files aren't locked
    systemctl stop meilisearch 2>/dev/null || true
    sleep 2
    
    # Remove everything in the directory
    find "$DATA_DIR" -mindepth 1 -delete 2>/dev/null || true
    # Also try rm -rf as fallback
    rm -rf "$DATA_DIR"/* "$DATA_DIR"/.[!.]* "$DATA_DIR"/..?* 2>/dev/null || true
    
    echo -e "${GREEN}Database cleared${NC}"
else
    echo -e "${YELLOW}Creating data directory...${NC}"
    mkdir -p "$DATA_DIR"
fi

# ALWAYS fix permissions after clearing
echo -e "${YELLOW}Setting proper permissions...${NC}"
chown -R $CURRENT_USER:$CURRENT_GROUP "$DATA_DIR" 2>/dev/null || true
chmod 755 "$DATA_DIR" 2>/dev/null || true
echo -e "${GREEN}Permissions set${NC}"

# Step 3: Get current user from service file
echo ""
echo -e "${YELLOW}Step 3: Reading service configuration...${NC}"
SERVICE_FILE="/etc/systemd/system/meilisearch.service"

if [ ! -f "$SERVICE_FILE" ]; then
    echo -e "${RED}Service file not found: $SERVICE_FILE${NC}"
    exit 1
fi

# Extract user, master key, and data dir from service file
CURRENT_USER=$(grep "^User=" "$SERVICE_FILE" | cut -d'=' -f2)
MASTER_KEY=$(grep "master-key=" "$SERVICE_FILE" | sed -n 's/.*--master-key="\([^"]*\)".*/\1/p')
DB_PATH=$(grep "db-path=" "$SERVICE_FILE" | sed -n 's/.*--db-path="\([^"]*\)".*/\1/p')

if [ -z "$CURRENT_USER" ]; then
    echo -e "${RED}Could not determine user from service file${NC}"
    exit 1
fi

CURRENT_GROUP=$(id -gn $CURRENT_USER 2>/dev/null || echo "$CURRENT_USER")

echo -e "${GREEN}User: $CURRENT_USER${NC}"
echo -e "${GREEN}Data directory: ${DB_PATH:-$DATA_DIR}${NC}"

# Step 4: Fix service file (remove problematic security settings)
echo ""
echo -e "${YELLOW}Step 4: Fixing service file...${NC}"

# Backup service file
cp "$SERVICE_FILE" "${SERVICE_FILE}.backup.$(date +%Y%m%d-%H%M%S)"
echo -e "${GREEN}Service file backed up${NC}"

# Create fixed service file
cat > "$SERVICE_FILE" << EOF
[Unit]
Description=Meilisearch
After=network.target

[Service]
Type=simple
User=$CURRENT_USER
Group=$CURRENT_GROUP
ExecStart=/usr/local/bin/meilisearch --env="production" --master-key="$MASTER_KEY" --db-path="${DB_PATH:-$DATA_DIR}" --http-addr="127.0.0.1:7700"
Restart=always
RestartSec=10
# Security settings (relaxed to avoid NAMESPACE errors)
NoNewPrivileges=true
PrivateTmp=false
# Removed ProtectSystem=strict as it causes NAMESPACE errors
ReadWritePaths=${DB_PATH:-$DATA_DIR}
StandardOutput=journal
StandardError=journal
SyslogIdentifier=meilisearch

[Install]
WantedBy=multi-user.target
EOF

echo -e "${GREEN}Service file updated${NC}"

# Step 5: Fix permissions
echo ""
echo -e "${YELLOW}Step 5: Fixing permissions...${NC}"
chown -R $CURRENT_USER:$CURRENT_GROUP "$DATA_DIR"
chmod 755 "$DATA_DIR"
echo -e "${GREEN}Permissions fixed${NC}"

# Step 6: Reload and start
echo ""
echo -e "${YELLOW}Step 6: Reloading systemd and starting service...${NC}"
systemctl daemon-reload
systemctl start meilisearch

# Step 7: Wait and check
sleep 3
echo ""
echo -e "${YELLOW}Step 7: Checking service status...${NC}"
if systemctl is-active --quiet meilisearch; then
    echo -e "${GREEN}✓ Meilisearch is running!${NC}"
    
    # Test health
    sleep 2
    HEALTH=$(curl -s http://127.0.0.1:7700/health 2>/dev/null || echo "failed")
    if echo "$HEALTH" | grep -q "available"; then
        echo -e "${GREEN}✓ Health check passed!${NC}"
    else
        echo -e "${YELLOW}⚠ Health check: $HEALTH${NC}"
    fi
else
    echo -e "${RED}✗ Meilisearch failed to start${NC}"
    echo ""
    echo "Recent logs:"
    journalctl -u meilisearch -n 20 --no-pager
    exit 1
fi

echo ""
echo "=========================================="
echo -e "${GREEN}Fix Complete!${NC}"
echo "=========================================="
echo ""
echo "Service is now running. Check status with:"
echo "  sudo systemctl status meilisearch"
echo ""

