#!/bin/bash

# Meilisearch Systemd Service Setup Script for AlmaLinux
# Run this after Meilisearch is installed

set -e

echo "=========================================="
echo "Meilisearch Systemd Service Setup"
echo "=========================================="
echo ""

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

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

# Verify Meilisearch is installed
if [ ! -f "/usr/local/bin/meilisearch" ]; then
    echo -e "${RED}Meilisearch not found at /usr/local/bin/meilisearch${NC}"
    echo "Please install Meilisearch first"
    exit 1
fi

echo -e "${GREEN}Meilisearch found at /usr/local/bin/meilisearch${NC}"
echo ""

# Get current user (for service file)
# When using 'sudo script.sh', SUDO_USER contains the original user
# When logged in as root directly, SUDO_USER is empty, so we need to ask
CURRENT_USER=${SUDO_USER:-$USER}

# Security: Services should not run as root
if [ "$CURRENT_USER" = "root" ]; then
    echo -e "${YELLOW}⚠️  Running as root. Services should run as a non-root user for security.${NC}"
    echo -e "${YELLOW}Please enter the username to run Meilisearch service (e.g., navanarel, www-data):${NC}"
    read -r CURRENT_USER
    if [ -z "$CURRENT_USER" ] || [ "$CURRENT_USER" = "root" ]; then
        echo -e "${RED}Error: A non-root username is required${NC}"
        exit 1
    fi
    # Verify user exists
    if ! id "$CURRENT_USER" &>/dev/null; then
        echo -e "${RED}Error: User '$CURRENT_USER' does not exist${NC}"
        exit 1
    fi
fi

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

echo -e "${GREEN}Service will run as user: $CURRENT_USER (group: $CURRENT_GROUP)${NC}"
echo ""

# Step 1: Create data directory
echo -e "${YELLOW}Step 1: Creating data directory...${NC}"
DATA_DIR="/var/lib/meilisearch"
mkdir -p $DATA_DIR
chown -R $CURRENT_USER:$CURRENT_GROUP $DATA_DIR
chmod 755 $DATA_DIR
echo -e "${GREEN}Data directory created: $DATA_DIR${NC}"

# Step 2: Generate master key
echo ""
echo -e "${YELLOW}Step 2: Generating master key...${NC}"
if command -v openssl &> /dev/null; then
    MASTER_KEY=$(openssl rand -base64 24 | tr -d '\n')
else
    MASTER_KEY=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
fi
echo -e "${GREEN}Master key generated${NC}"
echo ""
echo -e "${RED}════════════════════════════════════════${NC}"
echo -e "${RED}IMPORTANT: Save this master key securely!${NC}"
echo -e "${RED}════════════════════════════════════════${NC}"
echo -e "${GREEN}Master Key: $MASTER_KEY${NC}"
echo ""
read -p "Press Enter to continue after saving the key..."

# Step 3: Create systemd service file
echo ""
echo -e "${YELLOW}Step 3: Creating systemd service file...${NC}"
SERVICE_FILE="/etc/systemd/system/meilisearch.service"

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="$DATA_DIR" --http-addr="127.0.0.1:7700"
Restart=always
RestartSec=10
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=$DATA_DIR
StandardOutput=journal
StandardError=journal
SyslogIdentifier=meilisearch

[Install]
WantedBy=multi-user.target
EOF

echo -e "${GREEN}Service file created: $SERVICE_FILE${NC}"

# Step 4: Reload systemd and enable service
echo ""
echo -e "${YELLOW}Step 4: Enabling and starting service...${NC}"
systemctl daemon-reload
systemctl enable meilisearch

# Step 5: Start service
echo ""
echo -e "${YELLOW}Step 5: Starting Meilisearch service...${NC}"
systemctl start meilisearch

# Step 6: Wait a moment and check status
sleep 3
echo ""
echo -e "${YELLOW}Step 6: Checking service status...${NC}"
if systemctl is-active --quiet meilisearch; then
    echo -e "${GREEN}✓ Meilisearch is running!${NC}"
else
    echo -e "${RED}✗ Meilisearch failed to start${NC}"
    echo ""
    echo "Checking logs..."
    journalctl -u meilisearch -n 20 --no-pager
    exit 1
fi

# Step 7: Test health endpoint
echo ""
echo -e "${YELLOW}Step 7: Testing health endpoint...${NC}"
sleep 2
HEALTH_RESPONSE=$(curl -s http://127.0.0.1:7700/health || echo "failed")
if echo "$HEALTH_RESPONSE" | grep -q "available"; then
    echo -e "${GREEN}✓ Health check passed!${NC}"
    echo "Response: $HEALTH_RESPONSE"
else
    echo -e "${YELLOW}⚠ Health check returned: $HEALTH_RESPONSE${NC}"
    echo "Service is running but health endpoint may need more time"
fi

# Summary
echo ""
echo "=========================================="
echo -e "${GREEN}Setup Complete!${NC}"
echo "=========================================="
echo ""
echo "Service Information:"
echo "  - Service file: $SERVICE_FILE"
echo "  - Data directory: $DATA_DIR"
echo "  - Listening on: 127.0.0.1:7700"
echo "  - Running as: $CURRENT_USER:$CURRENT_GROUP"
echo ""
echo -e "${RED}════════════════════════════════════════${NC}"
echo -e "${RED}IMPORTANT: Save your master key!${NC}"
echo -e "${RED}════════════════════════════════════════${NC}"
echo -e "${GREEN}Master Key: $MASTER_KEY${NC}"
echo ""
echo "Useful Commands:"
echo "  - Check status: sudo systemctl status meilisearch"
echo "  - View logs: sudo journalctl -u meilisearch -f"
echo "  - Restart: sudo systemctl restart meilisearch"
echo "  - Stop: sudo systemctl stop meilisearch"
echo ""
echo "Next Steps:"
echo "  1. Add to Strapi CMS .env file:"
echo "     MEILISEARCH_HOST=http://127.0.0.1:7700"
echo "     MEILISEARCH_MASTER_KEY=$MASTER_KEY"
echo ""
echo "  2. Add to Next.js .env.production file:"
echo "     NEXT_PUBLIC_MEILISEARCH_HOST=http://127.0.0.1:7700"
echo ""
echo "  3. Restart Strapi CMS to sync data:"
echo "     pm2 restart nrel-cms"
echo "     # or"
echo "     sudo systemctl restart nrel-cms"
echo ""

