#!/bin/bash

# Automated Server Setup Script
# Run this script on your server via SSH

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${CYAN}╔════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║   Automated Admin Panel Setup         ║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════╝${NC}"
echo ""

# Configuration
APP_DIR="$HOME/public_html/manage.lehkhabu.in"
ZIP_FILE="ebook_admin_panel.zip"

# MongoDB Configuration
MONGO_HOST="169.150.218.18"
MONGO_PORT="27017"
MONGO_USER="brandkwikcom_db_user"
MONGO_PASS="iOjtoVd69qStHkyy"
MONGO_DB="Ebook"
MONGO_URI="mongodb://$MONGO_USER:$MONGO_PASS@$MONGO_HOST:$MONGO_PORT/$MONGO_DB?authSource=admin"

echo -e "${YELLOW}This script will:${NC}"
echo "1. Extract admin panel files"
echo "2. Install Node.js dependencies"
echo "3. Import database collections"
echo "4. Start the application"
echo ""

read -p "Continue? (y/n): " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${RED}Setup cancelled${NC}"
    exit 1
fi

# Step 1: Navigate to directory
echo ""
echo -e "${CYAN}Step 1: Navigating to application directory...${NC}"
if [ ! -d "$APP_DIR" ]; then
    echo -e "${RED}Directory not found: $APP_DIR${NC}"
    exit 1
fi

cd "$APP_DIR" || exit 1
echo -e "${GREEN}✓ In directory: $APP_DIR${NC}"

# Step 2: Extract files
echo ""
echo -e "${CYAN}Step 2: Extracting files...${NC}"
if [ -f "$ZIP_FILE" ]; then
    unzip -q -o "$ZIP_FILE"
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ Files extracted successfully${NC}"
        rm -f "$ZIP_FILE"
        echo -e "${GREEN}✓ Zip file removed${NC}"
    else
        echo -e "${RED}✗ Failed to extract files${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}⚠ Zip file not found, assuming files are already extracted${NC}"
fi

# Step 3: Verify .env file
echo ""
echo -e "${CYAN}Step 3: Verifying configuration...${NC}"
if [ -f ".env" ]; then
    echo -e "${GREEN}✓ .env file found${NC}"
else
    echo -e "${YELLOW}⚠ .env file not found, creating from .env.production${NC}"
    if [ -f ".env.production" ]; then
        cp .env.production .env
        # Update with MongoDB connection
        cat > .env << EOF
PORT = 8180
SESSION_SECRET = "ebook_secure_secret_$(date +%s)_production"
DB_CONNECTION="$MONGO_URI"
NODE_ENV=production
EOF
        echo -e "${GREEN}✓ .env file created${NC}"
    else
        echo -e "${RED}✗ .env.production not found${NC}"
        exit 1
    fi
fi

# Step 4: Check Node.js
echo ""
echo -e "${CYAN}Step 4: Checking Node.js...${NC}"
if command -v node &> /dev/null; then
    NODE_VERSION=$(node --version)
    echo -e "${GREEN}✓ Node.js installed: $NODE_VERSION${NC}"
else
    echo -e "${RED}✗ Node.js not found${NC}"
    echo -e "${YELLOW}Please install Node.js first${NC}"
    exit 1
fi

# Step 5: Install dependencies
echo ""
echo -e "${CYAN}Step 5: Installing dependencies...${NC}"
echo -e "${YELLOW}This may take 2-5 minutes...${NC}"

if npm install --production; then
    echo -e "${GREEN}✓ Dependencies installed successfully${NC}"
else
    echo -e "${RED}✗ Failed to install dependencies${NC}"
    exit 1
fi

# Step 6: Test MongoDB connection
echo ""
echo -e "${CYAN}Step 6: Testing MongoDB connection...${NC}"

# Create a test script
cat > test_mongo.js << 'TESTEOF'
const mongoose = require('mongoose');
const uri = process.env.DB_CONNECTION || process.argv[2];

mongoose.connect(uri)
    .then(() => {
        console.log('MongoDB connection successful');
        process.exit(0);
    })
    .catch((err) => {
        console.error('MongoDB connection failed:', err.message);
        process.exit(1);
    });

setTimeout(() => {
    console.error('Connection timeout');
    process.exit(1);
}, 10000);
TESTEOF

if node test_mongo.js "$MONGO_URI" 2>/dev/null; then
    echo -e "${GREEN}✓ MongoDB connection successful${NC}"
    rm -f test_mongo.js
else
    echo -e "${YELLOW}⚠ MongoDB connection test failed${NC}"
    echo -e "${YELLOW}  The app may still work if MongoDB is accessible from server${NC}"
    rm -f test_mongo.js
fi

# Step 7: Import database (if mongoimport available)
echo ""
echo -e "${CYAN}Step 7: Checking for database import tools...${NC}"

if command -v mongoimport &> /dev/null; then
    echo -e "${GREEN}✓ mongoimport found${NC}"
    echo -e "${YELLOW}Importing database collections...${NC}"
    
    # Note: Database files need to be uploaded separately
    echo -e "${YELLOW}⚠ Database JSON files need to be uploaded to import${NC}"
    echo -e "${YELLOW}  You can import them later using MongoDB Compass${NC}"
else
    echo -e "${YELLOW}⚠ mongoimport not found${NC}"
    echo -e "${YELLOW}  Import database using MongoDB Compass:${NC}"
    echo -e "${BLUE}  Connection: $MONGO_URI${NC}"
fi

# Step 8: Start application
echo ""
echo -e "${CYAN}Step 8: Starting application...${NC}"

# Check if PM2 is available
if command -v pm2 &> /dev/null; then
    echo -e "${GREEN}✓ PM2 found${NC}"
    
    # Stop existing instance if any
    pm2 delete ebook-admin 2>/dev/null
    
    # Start with PM2
    pm2 start app.js --name ebook-admin
    pm2 save
    
    echo -e "${GREEN}✓ Application started with PM2${NC}"
    echo ""
    echo -e "${YELLOW}Useful PM2 commands:${NC}"
    echo -e "${BLUE}  pm2 status          ${NC}- Check status"
    echo -e "${BLUE}  pm2 logs ebook-admin${NC}- View logs"
    echo -e "${BLUE}  pm2 restart ebook-admin${NC}- Restart app"
    
else
    echo -e "${YELLOW}⚠ PM2 not found${NC}"
    echo -e "${YELLOW}Starting with Node.js directly...${NC}"
    
    # Start in background
    nohup node app.js > app.log 2>&1 &
    APP_PID=$!
    
    echo -e "${GREEN}✓ Application started (PID: $APP_PID)${NC}"
    echo -e "${YELLOW}Note: Install PM2 for better process management:${NC}"
    echo -e "${BLUE}  npm install -g pm2${NC}"
fi

# Final summary
echo ""
echo -e "${CYAN}╔════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║          Setup Complete!               ║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════╝${NC}"
echo ""
echo -e "${GREEN}✓ Files extracted${NC}"
echo -e "${GREEN}✓ Dependencies installed${NC}"
echo -e "${GREEN}✓ Configuration verified${NC}"
echo -e "${GREEN}✓ Application started${NC}"
echo ""
echo -e "${CYAN}Access your admin panel at:${NC}"
echo -e "${BLUE}  https://manage.lehkhabu.in${NC}"
echo ""
echo -e "${CYAN}Default Login:${NC}"
echo -e "${BLUE}  Username: admin@gmail.com${NC}"
echo -e "${BLUE}  Password: 123${NC}"
echo ""
echo -e "${RED}⚠️  IMPORTANT:${NC}"
echo -e "${YELLOW}1. Import database collections using MongoDB Compass${NC}"
echo -e "${YELLOW}2. Change default admin password after login${NC}"
echo ""
echo -e "${CYAN}MongoDB Connection String:${NC}"
echo -e "${BLUE}$MONGO_URI${NC}"
echo ""
