#!/bin/bash
#
# 🚀 ROA2WEB Production Setup Script
# Automatic setup for production environment with security best practices
#

set -e

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

echo -e "${GREEN}"
echo "=============================================="
echo "🚀 ROA2WEB PRODUCTION SETUP"
echo "=============================================="
echo -e "${NC}"

# Function to print step headers
print_step() {
    echo -e "${BLUE}📋 Step $1: $2${NC}"
    echo "----------------------------------------"
}

# Function to generate strong passwords
generate_password() {
    local length=${1:-32}
    openssl rand -base64 $length | tr -d "=+/" | cut -c1-$length
}

# Function to generate JWT secret
generate_jwt_secret() {
    openssl rand -hex 32
}

# Check prerequisites
print_step "1" "Checking Prerequisites"

if ! command -v openssl &> /dev/null; then
    echo -e "${RED}❌ OpenSSL is required but not installed${NC}"
    exit 1
fi

if ! command -v docker &> /dev/null; then
    echo -e "${YELLOW}⚠️  Docker not found - you'll need to set up environment variables manually${NC}"
fi

echo -e "${GREEN}✅ Prerequisites check passed${NC}"
echo

# Generate production credentials
print_step "2" "Generating Production Credentials"

ORACLE_PASSWORD=$(generate_password 16)
JWT_SECRET=$(generate_jwt_secret)
REDIS_PASSWORD=$(generate_password 16)
MARIUS_PASSWORD=$(generate_password 12)
ELI_PASSWORD=$(generate_password 12)

echo -e "${GREEN}✅ Secure credentials generated${NC}"
echo

# Create production environment file
print_step "3" "Creating Production Environment File"

cat > .env.production << EOF
# 🔒 ROA2WEB Production Environment
# Generated: $(date)
# 
# ⚠️  SECURITY WARNING: 
# - Keep this file secure and never commit to git
# - Use environment-specific secret management in production
# - Rotate these credentials regularly

# Application Environment
ENVIRONMENT=production
DEBUG=false
NODE_ENV=production

# Oracle Database Configuration
# 🔐 IMPORTANT: These are the actual production credentials
ORACLE_USER=CONTAFIN_ORACLE
ORACLE_PASSWORD=${ORACLE_PASSWORD}
ORACLE_HOST=localhost  # Through SSH tunnel
ORACLE_PORT=1521
ORACLE_SID=ROA

# User Authentication Credentials
# 🔐 Update in your authentication system
MARIUS_PASSWORD=${MARIUS_PASSWORD}
ELI_PASSWORD=${ELI_PASSWORD}

# JWT Authentication
JWT_SECRET_KEY=${JWT_SECRET}
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=30

# Redis Configuration
REDIS_PASSWORD=${REDIS_PASSWORD}

# API Configuration
API_V1_STR=/api/v1
VITE_API_BASE_URL=https://your-domain.com/api

# SSL Configuration
DOMAIN=your-domain.com
SSL_EMAIL=admin@your-domain.com

# Frontend Configuration
VITE_APP_NAME=ROA2WEB Reports
VITE_APP_VERSION=1.0.0

# Production Performance Settings
WORKERS=4
MAX_CONNECTIONS=1000
DB_MIN_CONNECTIONS=5
DB_MAX_CONNECTIONS=20
DB_CONNECTION_INCREMENT=2

# Docker Configuration
COMPOSE_PROJECT_NAME=roa2web

# SSH Tunnel Configuration (for Oracle access)
SSH_SERVER=83.103.197.79
SSH_PORT=22122
SSH_USER=roa2web
REMOTE_HOST=10.0.20.36
REMOTE_PORT=1521
EOF

echo -e "${GREEN}✅ Production environment file created: .env.production${NC}"
echo

# Create credentials summary
print_step "4" "Creating Credentials Summary"

cat > PRODUCTION_CREDENTIALS.md << EOF
# 🔐 ROA2WEB Production Credentials

**Generated**: $(date)
**⚠️  SECURITY**: Store these credentials securely and delete this file after setup!

## Database Credentials
- **Oracle Password**: \`${ORACLE_PASSWORD}\`
- **Redis Password**: \`${REDIS_PASSWORD}\`

## Application Secrets
- **JWT Secret**: \`${JWT_SECRET}\`

## User Passwords (Update in Oracle database)
- **Marius**: \`${MARIUS_PASSWORD}\`
- **Eli**: \`${ELI_PASSWORD}\`

## Setup Instructions

### 1. Oracle Database
Update the Oracle password for CONTAFIN_ORACLE user:
\`\`\`sql
ALTER USER CONTAFIN_ORACLE IDENTIFIED BY "${ORACLE_PASSWORD}";
\`\`\`

### 2. User Authentication
Update user passwords in your authentication system:
- marius: ${MARIUS_PASSWORD}
- eli: ${ELI_PASSWORD}

### 3. Environment Variables
Set in your production environment:
\`\`\`bash
export ORACLE_PASSWORD="${ORACLE_PASSWORD}"
export JWT_SECRET_KEY="${JWT_SECRET}"
export REDIS_PASSWORD="${REDIS_PASSWORD}"
\`\`\`

### 4. SSH Key Setup
Make sure SSH key is in the correct location:
\`\`\`bash
# SSH key should be at:
roa2web/secrets/roa_oracle_server

# With correct permissions:
chmod 600 roa2web/secrets/roa_oracle_server
\`\`\`

### 5. Docker Deployment
\`\`\`bash
# Copy production environment
cp .env.production .env

# Start production stack
docker-compose -f docker-compose.yml -f docker-compose.production.yml up -d

# Check services
docker-compose ps
\`\`\`

## ⚠️  Security Checklist
- [ ] Oracle password updated in database
- [ ] User passwords updated in authentication system
- [ ] Environment variables set in production
- [ ] SSH key permissions verified (600)
- [ ] .env.production file secured (not in git)
- [ ] This credentials file deleted after setup
- [ ] Firewall rules configured
- [ ] SSL certificates installed
- [ ] Monitoring and logging configured

## 🔄 Regular Maintenance
- Rotate credentials every 90 days
- Monitor access logs
- Keep SSH keys up to date
- Regular security scans

---
*Generated by ROA2WEB Production Setup Script*
EOF

echo -e "${GREEN}✅ Credentials summary created: PRODUCTION_CREDENTIALS.md${NC}"
echo

# Create deployment script
print_step "5" "Creating Deployment Script"

cat > deploy_production.sh << 'EOF'
#!/bin/bash
#
# 🚀 ROA2WEB Production Deployment Script
#

set -e

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

echo -e "${GREEN}🚀 Starting ROA2WEB Production Deployment${NC}"

# Check if production environment exists
if [ ! -f ".env.production" ]; then
    echo -e "${RED}❌ .env.production not found. Run setup_production.sh first!${NC}"
    exit 1
fi

# Copy production environment
echo -e "${BLUE}📋 Setting up production environment...${NC}"
cp .env.production .env

# Check SSH key
if [ ! -f "secrets/roa_oracle_server" ]; then
    echo -e "${RED}❌ SSH key not found at secrets/roa_oracle_server${NC}"
    echo -e "${YELLOW}Please ensure SSH key is in the correct location with proper permissions${NC}"
    exit 1
fi

# Set SSH key permissions
chmod 600 secrets/roa_oracle_server
echo -e "${GREEN}✅ SSH key permissions set${NC}"

# Pull latest images
echo -e "${BLUE}📋 Pulling latest Docker images...${NC}"
docker-compose pull

# Build services
echo -e "${BLUE}📋 Building services...${NC}"
docker-compose build --no-cache

# Start services
echo -e "${BLUE}📋 Starting production services...${NC}"
docker-compose -f docker-compose.yml -f docker-compose.production.yml up -d

# Wait for services to start
echo -e "${BLUE}📋 Waiting for services to start...${NC}"
sleep 30

# Health check
echo -e "${BLUE}📋 Running health checks...${NC}"
if curl -f http://localhost/health >/dev/null 2>&1; then
    echo -e "${GREEN}✅ Application is healthy and running!${NC}"
else
    echo -e "${YELLOW}⚠️  Health check failed, checking service status...${NC}"
    docker-compose ps
fi

# Show final status
echo -e "${GREEN}"
echo "=============================================="
echo "🎉 ROA2WEB PRODUCTION DEPLOYMENT COMPLETE"
echo "=============================================="
echo -e "${NC}"
echo -e "${BLUE}Services Status:${NC}"
docker-compose ps

echo
echo -e "${BLUE}Access Points:${NC}"
echo -e "  🌐 Web Application: http://localhost"
echo -e "  📊 API Documentation: http://localhost/docs"
echo -e "  🔧 Admin Interface: http://localhost:8080"

echo
echo -e "${YELLOW}Next Steps:${NC}"
echo -e "  1. 🔐 Update Oracle database password"
echo -e "  2. 🔑 Update user authentication passwords"
echo -e "  3. 🌍 Configure domain and SSL certificates"
echo -e "  4. 📊 Set up monitoring and logging"
echo -e "  5. 🗑️  Delete PRODUCTION_CREDENTIALS.md after setup"
EOF

chmod +x deploy_production.sh
echo -e "${GREEN}✅ Deployment script created: deploy_production.sh${NC}"
echo

# Final instructions
print_step "6" "Setup Complete - Next Steps"

echo -e "${GREEN}🎉 Production setup completed successfully!${NC}"
echo
echo -e "${BLUE}Files Created:${NC}"
echo -e "  📄 .env.production - Production environment variables"
echo -e "  📄 PRODUCTION_CREDENTIALS.md - Secure credentials summary"
echo -e "  🚀 deploy_production.sh - Deployment script"
echo
echo -e "${YELLOW}⚠️  IMPORTANT SECURITY STEPS:${NC}"
echo -e "  1. 🔐 Review PRODUCTION_CREDENTIALS.md and update systems"
echo -e "  2. 🔑 Change Oracle password: ALTER USER CONTAFIN_ORACLE IDENTIFIED BY 'new_password'"
echo -e "  3. 👥 Update user passwords in authentication system"
echo -e "  4. 🔒 Secure .env.production file (proper permissions)"
echo -e "  5. 🗑️  DELETE PRODUCTION_CREDENTIALS.md after setup"
echo
echo -e "${BLUE}To Deploy:${NC}"
echo -e "  ./deploy_production.sh"
echo
echo -e "${GREEN}✅ ROA2WEB is ready for production deployment!${NC}"