# Vision Videoke EC2 Deployment Guide

## Table of Contents
1. [Overview](#overview)
2. [Prerequisites](#prerequisites)
3. [EC2 Instance Setup](#ec2-instance-setup)
4. [Installation Methods](#installation-methods)
5. [Configuration](#configuration)
6. [SSL Setup](#ssl-setup)
7. [Application Deployment](#application-deployment)
8. [Monitoring & Maintenance](#monitoring--maintenance)
9. [Troubleshooting](#troubleshooting)
10. [Security Considerations](#security-considerations)

## Overview

This guide provides complete instructions for deploying Vision Videoke on Amazon EC2 with Amazon Linux. The deployment includes:

- **Automated Installation**: One-click installer for customers
- **Production-Ready Configuration**: Nginx, SSL, security hardening
- **Monitoring & Backup**: Automated health checks and backups
- **Scalable Architecture**: PM2 cluster mode for high availability

## Prerequisites

### AWS Account Setup
- Active AWS account with EC2 access
- Understanding of AWS security groups and networking
- Domain name registered and managed through Route 53 (recommended)

### Technical Requirements
- **Instance Type**: t3.medium minimum (2 vCPUs, 4GB RAM)
- **Operating System**: Amazon Linux 2
- **Storage**: 20GB+ EBS volume (gp3 recommended)
- **Network**: VPC with public subnet and internet gateway

### API Keys Required
- **OpenAI API Key**: For AI-powered lyric generation
- **Udio API Key**: For music generation
- **ElevenLabs API Key**: For voice cloning
- **Stripe Keys**: For payment processing (optional)

### Domain Configuration
- Domain name purchased and configured
- DNS management access
- SSL certificate email address

## EC2 Instance Setup

### Step 1: Launch EC2 Instance

1. **Choose AMI**: Amazon Linux 2 AMI (HVM), SSD Volume Type
2. **Instance Type**: t3.medium or larger
3. **Configure Instance**:
   - Network: Default VPC or custom VPC with internet access
   - Subnet: Public subnet
   - Auto-assign Public IP: Enable
4. **Add Storage**: 20GB gp3 EBS volume (minimum)
5. **Add Tags**: 
   - Name: VisionVideoke-Production
   - Environment: Production
   - Application: VisionVideoke
6. **Configure Security Group**:
   ```
   Type        Protocol    Port Range    Source
   SSH         TCP         22           Your IP/0.0.0.0/0
   HTTP        TCP         80           0.0.0.0/0
   HTTPS       TCP         443          0.0.0.0/0
   Custom TCP  TCP         3000         127.0.0.1/32 (for health checks)
   ```
7. **Review and Launch**: Select or create key pair

### Step 2: Connect to Instance

```bash
# Connect via SSH
ssh -i your-key.pem ec2-user@your-instance-public-ip

# Update system (recommended)
sudo yum update -y
```

### Step 3: Configure Domain DNS

Point your domain to the EC2 instance:

**Route 53 (Recommended):**
1. Go to Route 53 console
2. Select your hosted zone
3. Create A record:
   - Name: @ (or subdomain)
   - Type: A
   - Value: EC2 instance public IP
   - TTL: 300

**Other DNS Providers:**
- Create A record pointing to EC2 public IP
- Wait for DNS propagation (up to 24 hours)

## Installation Methods

### Method 1: One-Click Customer Installer (Recommended)

This is the easiest method for customers:

```bash
# Download installer package
wget https://your-distribution-server.com/VisionVideoke-EC2-Installer-1.0.0.tar.gz

# Verify checksum (optional but recommended)
sha256sum VisionVideoke-EC2-Installer-1.0.0.tar.gz

# Extract package
tar -xzf VisionVideoke-EC2-Installer-1.0.0.tar.gz

# Run installer
cd VisionVideoke-EC2-Installer-1.0.0
./customer-installer.sh
```

The installer will:
1. Prompt for domain name and email
2. Request API keys
3. Install all required software
4. Configure security settings
5. Set up SSL certificate
6. Deploy the application
7. Configure monitoring

### Method 2: Manual Installation

For advanced users or custom configurations:

```bash
# Download deployment scripts
git clone https://github.com/your-repo/vision-videoke-deploy.git
cd vision-videoke-deploy

# Run individual setup scripts
./scripts/ec2-setup.sh
./scripts/configure-nginx.sh your-domain.com
./scripts/production-config.sh
./scripts/build-and-deploy.sh
```

### Method 3: Advanced Installation

For enterprise deployments with additional features:

```bash
# Use advanced installer
./advanced-installer.sh
```

This includes:
- PostgreSQL database setup
- Redis caching
- CloudWatch monitoring
- Load balancer configuration
- Auto-scaling setup

## Configuration

### Environment Variables

After installation, configure the application in `/var/www/visionvideoke/.env`:

```bash
# Edit environment file
nano /var/www/visionvideoke/.env
```

**Required Configuration:**
```env
# API Keys (REQUIRED)
REACT_APP_OPENAI_API_KEY=your_openai_api_key_here
REACT_APP_UDIO_API_KEY=your_udio_api_key_here
REACT_APP_ELEVENLABS_API_KEY=your_elevenlabs_api_key_here

# Domain Configuration
DOMAIN_NAME=your-domain.com
REACT_APP_API_URL=https://your-domain.com/api
REACT_APP_APP_URL=https://your-domain.com

# Payment Processing (Optional)
REACT_APP_STRIPE_PUBLISHABLE_KEY=pk_live_your_stripe_key
STRIPE_SECRET_KEY=sk_live_your_stripe_secret
```

**Optional Configuration:**
```env
# Database (for user management)
DATABASE_URL=postgresql://user:password@localhost:5432/visionvideoke

# File Storage (AWS S3)
AWS_ACCESS_KEY_ID=your_aws_access_key
AWS_SECRET_ACCESS_KEY=your_aws_secret_key
AWS_REGION=us-east-1
AWS_S3_BUCKET=visionvideoke-uploads

# Monitoring
SENTRY_DSN=your_sentry_dsn_here

# Feature Flags
REACT_APP_ENABLE_VOICE_CLONING=true
REACT_APP_ENABLE_VIDEO_GENERATION=true
REACT_APP_ENABLE_PAYMENTS=true
```

### Nginx Configuration

The installer automatically configures Nginx, but you can customize:

```bash
# Edit Nginx configuration
sudo nano /etc/nginx/sites-available/visionvideoke

# Test configuration
sudo nginx -t

# Reload configuration
sudo systemctl reload nginx
```

### PM2 Configuration

Application process management is handled by PM2:

```bash
# View PM2 configuration
cat /var/www/visionvideoke/ecosystem.config.js

# PM2 commands
pm2 status          # Check application status
pm2 logs            # View logs
pm2 restart all     # Restart application
pm2 reload all      # Zero-downtime reload
pm2 monit           # Monitor resources
```

## SSL Setup

### Automatic SSL (Recommended)

The installer automatically sets up SSL using Let's Encrypt:

```bash
# SSL is configured during installation
# Certificate auto-renewal is set up via cron
```

### Manual SSL Setup

If SSL setup failed during installation:

```bash
# Run SSL setup script
./setup-ssl.sh your-domain.com your-email@domain.com

# Or manually with certbot
sudo systemctl stop nginx
sudo certbot certonly --standalone -d your-domain.com --email your-email@domain.com --agree-tos
sudo systemctl start nginx
```

### SSL Certificate Management

```bash
# Check certificate status
sudo certbot certificates

# Test auto-renewal
sudo certbot renew --dry-run

# Manual renewal
sudo certbot renew

# View certificate details
openssl x509 -in /etc/letsencrypt/live/your-domain.com/fullchain.pem -text -noout
```

## Application Deployment

### Initial Deployment

After system setup, deploy the Vision Videoke application:

```bash
# Upload application files to deployment directory
# Option 1: From local development
scp -r ./MusicPlatformWeb/* ec2-user@your-server:/tmp/visionvideoke-upload/

# Option 2: From GitHub repository
./build-and-deploy.sh github https://github.com/your-repo/vision-videoke.git main

# Option 3: From uploaded source
./build-and-deploy.sh source /tmp/visionvideoke-upload
```

### Application Updates

To update the application:

```bash
# Using the update script
./update-app.sh

# Or using the deployment script
./build-and-deploy.sh source /path/to/new/source

# Zero-downtime deployment
pm2 reload all
```

### Build Process

The deployment script automatically:
1. Installs dependencies (`npm ci`)
2. Builds the application (`npm run build`)
3. Configures PM2 ecosystem
4. Starts/restarts the application
5. Updates Nginx configuration
6. Runs health checks

## Monitoring & Maintenance

### Health Monitoring

Automated health checks are configured:

```bash
# Manual health check
curl http://localhost:3000/health

# View health check logs
tail -f /var/log/visionvideoke/health.log

# Check application status
./status.sh
```

### Log Management

Application logs are automatically rotated:

```bash
# View application logs
pm2 logs

# View specific log files
tail -f /var/log/visionvideoke/combined.log
tail -f /var/log/visionvideoke/error.log
tail -f /var/log/nginx/visionvideoke_access.log
tail -f /var/log/nginx/visionvideoke_error.log
```

### Backup System

Automated backups are configured:

```bash
# Manual backup
./backup.sh

# View backups
ls -la /var/backups/visionvideoke/

# Restore from backup
tar -xzf /var/backups/visionvideoke/backup-YYYYMMDD-HHMMSS.tar.gz -C /var/www/visionvideoke/
pm2 restart all
```

### Performance Monitoring

```bash
# System resources
htop
free -h
df -h

# Application performance
pm2 monit

# Network monitoring
sudo netstat -tlnp
sudo ss -tlnp

# Performance optimization
./optimize-performance.sh
```

### Maintenance Tasks

**Daily:**
- Check application status
- Review error logs
- Monitor disk space

**Weekly:**
- Review access logs
- Check SSL certificate status
- Update system packages

**Monthly:**
- Clean old log files
- Review backup retention
- Security updates
- Performance optimization

```bash
# Weekly maintenance script
#!/bin/bash
echo "=== Weekly Maintenance ==="

# Check system status
./status.sh

# Clean old logs (older than 30 days)
find /var/log/visionvideoke -name "*.log" -mtime +30 -delete
sudo find /var/log/nginx -name "*.log" -mtime +30 -delete

# Clean old backups (older than 30 days)
find /var/backups/visionvideoke -name "*.tar.gz" -mtime +30 -delete

# Update system packages
sudo yum update -y

# Restart services
pm2 restart all
sudo systemctl reload nginx

echo "Maintenance completed"
```

## Troubleshooting

### Common Issues

**Application won't start:**
```bash
# Check PM2 status
pm2 status

# View error logs
pm2 logs

# Check environment file
cat /var/www/visionvideoke/.env

# Restart application
pm2 restart all
```

**502 Bad Gateway:**
```bash
# Check if application is running
pm2 status
curl http://localhost:3000/health

# Check Nginx configuration
sudo nginx -t

# Restart services
pm2 restart all
sudo systemctl restart nginx
```

**SSL Certificate Issues:**
```bash
# Check certificate status
sudo certbot certificates

# Renew certificate
sudo certbot renew

# Check Nginx SSL configuration
sudo nginx -t
```

**High Memory Usage:**
```bash
# Check memory usage
free -h
pm2 monit

# Restart with memory limit
pm2 restart all --max-memory-restart 1G

# Check for memory leaks
pm2 logs --lines 100 | grep -i memory
```

### Log Analysis

```bash
# Search for errors
grep -i error /var/log/visionvideoke/*.log
sudo grep -i error /var/log/nginx/*.log

# Monitor logs in real-time
tail -f /var/log/visionvideoke/combined.log

# Analyze access patterns
sudo tail -f /var/log/nginx/visionvideoke_access.log
```

### Emergency Recovery

If the system becomes unresponsive:

1. **Reboot EC2 instance** from AWS console
2. **Check system logs** after reboot:
   ```bash
   sudo tail -f /var/log/messages
   ```
3. **Restart all services**:
   ```bash
   pm2 restart all
   sudo systemctl restart nginx
   ```
4. **Restore from backup** if needed:
   ```bash
   ./restore-backup.sh
   ```

## Security Considerations

### Firewall Configuration

The installer configures firewalld with minimal required ports:

```bash
# Check firewall status
sudo firewall-cmd --list-all

# Add custom rules if needed
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload
```

### Fail2ban Configuration

Intrusion prevention is configured automatically:

```bash
# Check fail2ban status
sudo fail2ban-client status

# View banned IPs
sudo fail2ban-client status sshd
sudo fail2ban-client status nginx-http-auth
```

### Security Updates

```bash
# Regular security updates
sudo yum update -y --security

# Check for available updates
sudo yum check-update

# Enable automatic security updates
sudo yum install -y yum-cron
sudo systemctl enable yum-cron
sudo systemctl start yum-cron
```

### File Permissions

Ensure proper file permissions:

```bash
# Application files
sudo chown -R ec2-user:ec2-user /var/www/visionvideoke
chmod 644 /var/www/visionvideoke/.env

# Log files
sudo chown -R ec2-user:ec2-user /var/log/visionvideoke
chmod 644 /var/log/visionvideoke/*.log

# Backup files
sudo chown -R ec2-user:ec2-user /var/backups/visionvideoke
chmod 600 /var/backups/visionvideoke/*.tar.gz
```

### Additional Security Measures

1. **Change default SSH port** (optional):
   ```bash
   sudo nano /etc/ssh/sshd_config
   # Change Port 22 to Port 2222
   sudo systemctl restart sshd
   ```

2. **Disable password authentication**:
   ```bash
   sudo nano /etc/ssh/sshd_config
   # Set PasswordAuthentication no
   sudo systemctl restart sshd
   ```

3. **Enable CloudTrail** for AWS API logging
4. **Use IAM roles** instead of access keys when possible
5. **Regular security audits** and penetration testing

## Performance Optimization

### System Optimization

```bash
# Run performance optimization script
./optimize-performance.sh
```

This script optimizes:
- Node.js memory settings
- Nginx worker processes
- System kernel parameters
- File descriptor limits

### Application Optimization

1. **Enable PM2 cluster mode** (already configured)
2. **Use CDN** for static assets (CloudFront recommended)
3. **Database optimization** if using PostgreSQL
4. **Caching** with Redis for session management
5. **Load balancing** for high-traffic deployments

### Monitoring and Alerting

Set up CloudWatch monitoring:

```bash
# Install CloudWatch agent
wget https://s3.amazonaws.com/amazoncloudwatch-agent/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm
sudo rpm -U ./amazon-cloudwatch-agent.rpm

# Configure CloudWatch agent
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
```

## Scaling Considerations

### Vertical Scaling

Upgrade EC2 instance type:
1. Stop instance
2. Change instance type (t3.medium → t3.large → t3.xlarge)
3. Start instance
4. No configuration changes needed

### Horizontal Scaling

For high-traffic deployments:
1. **Application Load Balancer** with multiple EC2 instances
2. **Auto Scaling Group** for automatic scaling
3. **RDS** for shared database
4. **ElastiCache** for shared session storage
5. **S3** for file uploads and static assets

### Database Scaling

If using PostgreSQL:
1. **RDS** for managed database
2. **Read replicas** for read scaling
3. **Connection pooling** with PgBouncer
4. **Database optimization** and indexing

## Conclusion

This deployment guide provides comprehensive instructions for setting up Vision Videoke on Amazon EC2. The automated installer makes deployment simple for customers, while the manual methods provide flexibility for advanced configurations.

Key benefits of this deployment:
- **Production-ready** with security hardening
- **Automated monitoring** and health checks
- **SSL encryption** with auto-renewal
- **Backup system** for data protection
- **Scalable architecture** for growth
- **Comprehensive documentation** for maintenance

For additional support or custom deployment requirements, refer to the troubleshooting guide or contact technical support.

