#!/bin/bash
# MongoDB Installation Script

echo "=== MongoDB Installation ==="
echo ""

# Step 1: Create directories
echo "Step 1: Creating directories..."
sudo mkdir -p /Users/accusys/momentry/var
sudo mkdir -p /Users/accusys/momentry/log
sudo chown -R accusys:staff /Users/accusys/momentry
echo "   ✓ Directories created"

# Step 2: Check and backup existing plist
echo ""
echo "Step 2: Checking existing plist..."
PLIST_PATH="/Library/LaunchDaemons/com.momentry.mongodb.plist"
if [ -f "$PLIST_PATH" ]; then
    BACKUP_NAME="${PLIST_PATH}.$(date +%Y%m%d%H%M%S).bak"
    echo "   Backing up existing plist to: $BACKUP_NAME"
    sudo mv "$PLIST_PATH" "$BACKUP_NAME"
    echo "   ✓ Existing plist backed up"
else
    echo "   ✓ No existing plist found"
fi

# Step 3: Copy new plist
echo ""
echo "Step 3: Copying new plist..."
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_PLIST="$SCRIPT_DIR/momentry_runtime/plist/com.momentry.mongodb.plist"

if [ -f "$SOURCE_PLIST" ]; then
    sudo cp "$SOURCE_PLIST" /Library/LaunchDaemons/
    echo "   ✓ plist copied"
else
    echo "   ✗ Source plist not found: $SOURCE_PLIST"
    exit 1
fi

# Step 4: Start MongoDB
echo ""
echo "Step 4: Starting MongoDB..."
sudo launchctl load /Library/LaunchDaemons/com.momentry.mongodb.plist
echo "   ✓ MongoDB started"

# Step 5: Verify
echo ""
echo "Step 5: Verifying..."
sleep 2

echo ""
echo "   Port 27017 status:"
lsof -i :27017 || echo "   (checking...)"

echo ""
echo "   Service status:"
sudo launchctl list | grep momentry || echo "   No service found"

# Step 6: Create user (without auth first)
echo ""
echo "Step 6: Creating database user..."
mongosh --eval '
use admin
db.createUser({
  user: "accusys",
  pwd: "Test3200Test3200",
  roles: [{ role: "root", db: "admin" }]
})
' 2>/dev/null || echo "   (user creation deferred - MongoDB may still be starting)"

echo ""
echo "=== Installation Complete ==="
echo ""
echo "Connection string:"
echo "  mongodb://accusys:Test3200Test3200@localhost:27017/momentry"
echo ""
echo "Remote access enabled (bind_ip: 0.0.0.0)"
