#!/bin/bash

# Vision Videoke Package Creator
# Creates customer-ready installation packages

set -e

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

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

error() {
    echo -e "${RED}[ERROR] $1${NC}"
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARNING] $1${NC}"
}

info() {
    echo -e "${BLUE}[INFO] $1${NC}"
}

# Configuration
PACKAGE_NAME="VisionVideoke-EC2-Installer"
VERSION="1.0.0"
BUILD_DIR="/tmp/visionvideoke-package-build"
DIST_DIR="/tmp/visionvideoke-distribution"
SOURCE_DIR="/home/ubuntu/EC2-VisionVideoke-Deploy"
APP_SOURCE_DIR="/home/ubuntu/MusicPlatformWeb"

# Function to create package structure
create_package_structure() {
    log "Creating package structure..."
    
    # Clean and create build directory
    rm -rf $BUILD_DIR
    mkdir -p $BUILD_DIR
    
    # Create package directories
    mkdir -p $BUILD_DIR/{scripts,config,app,docs,templates}
    
    log "Package structure created"
}

# Function to copy installation scripts
copy_scripts() {
    log "Copying installation scripts..."
    
    # Copy all scripts
    cp -r $SOURCE_DIR/scripts/* $BUILD_DIR/scripts/
    
    # Copy customer installer
    cp $SOURCE_DIR/installers/customer-installer.sh $BUILD_DIR/
    
    # Make all scripts executable
    chmod +x $BUILD_DIR/scripts/*.sh
    chmod +x $BUILD_DIR/customer-installer.sh
    
    log "Scripts copied successfully"
}

# Function to copy configuration files
copy_configs() {
    log "Copying configuration files..."
    
    # Copy nginx and other configs
    cp -r $SOURCE_DIR/config/* $BUILD_DIR/config/
    
    # Copy templates
    cp -r $SOURCE_DIR/templates/* $BUILD_DIR/templates/ 2>/dev/null || true
    
    log "Configuration files copied"
}

# Function to prepare application package
prepare_app_package() {
    log "Preparing application package..."
    
    if [ -d "$APP_SOURCE_DIR" ]; then
        # Create application package
        cd $APP_SOURCE_DIR
        
        # Build the application
        if [ -f "package.json" ]; then
            info "Building application..."
            npm ci > /dev/null 2>&1 || warn "npm ci failed, continuing..."
            npm run build > /dev/null 2>&1 || warn "Build failed, continuing..."
        fi
        
        # Create application archive
        tar -czf $BUILD_DIR/app/visionvideoke-app.tar.gz \
            --exclude=node_modules \
            --exclude=.git \
            --exclude=.env* \
            --exclude=dist \
            --exclude=build \
            . 2>/dev/null || warn "Application packaging failed"
        
        log "Application package created"
    else
        warn "Application source directory not found: $APP_SOURCE_DIR"
        # Create placeholder
        mkdir -p $BUILD_DIR/app
        echo "Application package will be downloaded during installation" > $BUILD_DIR/app/README.txt
    fi
}

# Function to create documentation
create_documentation() {
    log "Creating documentation..."
    
    # Create main README
    cat > $BUILD_DIR/README.md <<EOF
# Vision Videoke EC2 Installer

## Overview

This package contains everything needed to install Vision Videoke on an Amazon Linux EC2 instance.

## Quick Start

1. Upload this package to your EC2 instance
2. Extract: \`tar -xzf ${PACKAGE_NAME}-${VERSION}.tar.gz\`
3. Run: \`cd ${PACKAGE_NAME}-${VERSION} && ./customer-installer.sh\`

## What's Included

- **customer-installer.sh** - One-click installer script
- **scripts/** - System setup and configuration scripts
- **config/** - Nginx and system configuration files
- **app/** - Vision Videoke application package
- **docs/** - Complete documentation

## System Requirements

- Amazon Linux EC2 instance (t3.medium or larger recommended)
- At least 2GB RAM and 20GB storage
- Domain name pointed to the server
- API keys for OpenAI, Udio, and ElevenLabs

## Installation Process

The installer will:
1. Update system packages
2. Install Node.js, PM2, and Nginx
3. Configure security (firewall, fail2ban)
4. Set up SSL certificates
5. Deploy the Vision Videoke application
6. Configure monitoring and backups

## Post-Installation

After installation:
1. Upload your application files to \`/var/www/visionvideoke/\`
2. Update API keys in \`/var/www/visionvideoke/.env\`
3. Test your platform at \`https://your-domain.com\`

## Support

- Check status: \`./status.sh\`
- View logs: \`pm2 logs\`
- Create backup: \`./backup.sh\`
- Update app: \`./update-app.sh\`

## Version

Version: ${VERSION}
Build Date: $(date)
EOF

    # Create installation guide
    cat > $BUILD_DIR/docs/INSTALLATION_GUIDE.md <<EOF
# Vision Videoke Installation Guide

## Prerequisites

### EC2 Instance Requirements
- **Instance Type**: t3.medium or larger (minimum 2 vCPUs, 4GB RAM)
- **Operating System**: Amazon Linux 2
- **Storage**: At least 20GB EBS volume
- **Security Group**: Allow ports 22 (SSH), 80 (HTTP), 443 (HTTPS)

### Domain Setup
1. Purchase a domain name
2. Point your domain's A record to your EC2 instance's public IP
3. Wait for DNS propagation (up to 24 hours)

### 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)

## Step-by-Step Installation

### Step 1: Connect to Your EC2 Instance
\`\`\`bash
ssh -i your-key.pem ec2-user@your-server-ip
\`\`\`

### Step 2: Upload Installation Package
\`\`\`bash
# Option 1: Using SCP
scp -i your-key.pem ${PACKAGE_NAME}-${VERSION}.tar.gz ec2-user@your-server-ip:~/

# Option 2: Using wget (if hosted)
wget https://your-distribution-server.com/${PACKAGE_NAME}-${VERSION}.tar.gz
\`\`\`

### Step 3: Extract and Run Installer
\`\`\`bash
tar -xzf ${PACKAGE_NAME}-${VERSION}.tar.gz
cd ${PACKAGE_NAME}-${VERSION}
./customer-installer.sh
\`\`\`

### Step 4: Follow Installation Prompts
The installer will ask for:
- Domain name
- Email for SSL certificate
- API keys
- Payment processing keys (optional)

### Step 5: Upload Application Files
After installation, upload your Vision Videoke application:
\`\`\`bash
# Extract application to the web directory
cd /var/www/visionvideoke
# Upload and extract your application files here
\`\`\`

### Step 6: Configure Environment
Edit the environment file:
\`\`\`bash
nano /var/www/visionvideoke/.env
\`\`\`

Update the API keys and other configuration as needed.

### Step 7: Restart Application
\`\`\`bash
pm2 restart all
\`\`\`

## Post-Installation Configuration

### SSL Certificate
If SSL setup failed during installation, run manually:
\`\`\`bash
./setup-ssl.sh your-domain.com
\`\`\`

### Application Updates
To update the application:
\`\`\`bash
./update-app.sh
\`\`\`

### Monitoring
Check system status:
\`\`\`bash
./status.sh
\`\`\`

View application logs:
\`\`\`bash
pm2 logs
\`\`\`

### Backups
Create manual backup:
\`\`\`bash
./backup.sh
\`\`\`

Backups are automatically created daily at 2 AM.

## Troubleshooting

### Common Issues

**Application not starting:**
\`\`\`bash
pm2 restart all
pm2 logs
\`\`\`

**Nginx errors:**
\`\`\`bash
sudo nginx -t
sudo systemctl status nginx
\`\`\`

**SSL certificate issues:**
\`\`\`bash
sudo certbot certificates
sudo certbot renew --dry-run
\`\`\`

**Domain not resolving:**
- Check DNS settings
- Verify A record points to correct IP
- Wait for DNS propagation

### Log Locations
- Application logs: \`/var/log/visionvideoke/\`
- Nginx logs: \`/var/log/nginx/\`
- System logs: \`/var/log/messages\`

### Support Commands
\`\`\`bash
# Check all services
./status.sh

# Restart everything
pm2 restart all
sudo systemctl restart nginx

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

# Check disk space
df -h

# Check memory usage
free -h
\`\`\`

## Security Considerations

The installer automatically configures:
- Firewall (firewalld) with minimal required ports
- Fail2ban for intrusion prevention
- SSL/TLS encryption
- Secure file permissions

### Additional Security Recommendations
1. Change default SSH port
2. Use key-based authentication only
3. Regular security updates
4. Monitor access logs
5. Use strong passwords for all accounts

## Performance Optimization

For high-traffic deployments:
1. Use larger EC2 instance types
2. Enable CloudFront CDN
3. Use RDS for database
4. Implement load balancing
5. Monitor with CloudWatch

## Maintenance

### Regular Tasks
- Monitor disk space
- Review access logs
- Update SSL certificates (automatic)
- Create backups (automatic)
- Update system packages monthly

### Monthly Maintenance
\`\`\`bash
# Update system
sudo yum update -y

# Clean old logs
sudo find /var/log -name "*.log" -mtime +30 -delete

# Clean old backups
find /var/backups/visionvideoke -name "*.tar.gz" -mtime +30 -delete
\`\`\`
EOF

    # Create troubleshooting guide
    cat > $BUILD_DIR/docs/TROUBLESHOOTING.md <<EOF
# Vision Videoke Troubleshooting Guide

## Common Issues and Solutions

### Installation Issues

#### "Permission denied" errors
\`\`\`bash
# Make sure you're running as ec2-user, not root
whoami  # Should return "ec2-user"

# If running as root, switch to ec2-user
su - ec2-user
\`\`\`

#### "Node.js not found" after installation
\`\`\`bash
# Reload shell environment
source ~/.bashrc

# Or restart your SSH session
exit
ssh -i your-key.pem ec2-user@your-server-ip
\`\`\`

#### SSL certificate fails
\`\`\`bash
# Check if domain points to your server
nslookup your-domain.com

# Check if ports 80 and 443 are open
sudo netstat -tlnp | grep :80
sudo netstat -tlnp | grep :443

# Manually obtain certificate
sudo certbot certonly --standalone -d your-domain.com
\`\`\`

### Application Issues

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

# View error logs
pm2 logs

# Restart application
pm2 restart all

# If still failing, check environment file
cat /var/www/visionvideoke/.env
\`\`\`

#### "Cannot connect to API" errors
\`\`\`bash
# Check API keys in environment file
grep API_KEY /var/www/visionvideoke/.env

# Test API connectivity
curl -H "Authorization: Bearer YOUR_OPENAI_KEY" https://api.openai.com/v1/models
\`\`\`

#### High memory usage
\`\`\`bash
# Check memory usage
free -h

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

# Check for memory leaks
pm2 monit
\`\`\`

### Web Server Issues

#### Nginx won't start
\`\`\`bash
# Test nginx configuration
sudo nginx -t

# Check nginx status
sudo systemctl status nginx

# View nginx error logs
sudo tail -f /var/log/nginx/error.log
\`\`\`

#### 502 Bad Gateway error
\`\`\`bash
# Check if application is running
pm2 status

# Check if application is listening on port 3000
sudo netstat -tlnp | grep :3000

# Restart both nginx and application
pm2 restart all
sudo systemctl restart nginx
\`\`\`

#### SSL certificate expired
\`\`\`bash
# Check certificate status
sudo certbot certificates

# Renew certificate
sudo certbot renew

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

### Performance Issues

#### Slow response times
\`\`\`bash
# Check system resources
htop

# Check disk I/O
iostat -x 1

# Check network connectivity
ping google.com

# Optimize PM2 cluster mode
pm2 delete all
pm2 start ecosystem.config.js
\`\`\`

#### High CPU usage
\`\`\`bash
# Identify high CPU processes
top

# Check PM2 processes
pm2 monit

# Restart application
pm2 restart all
\`\`\`

### Database Issues (if using)

#### Cannot connect to database
\`\`\`bash
# Check database URL in environment
grep DATABASE_URL /var/www/visionvideoke/.env

# Test database connection
psql \$DATABASE_URL -c "SELECT 1;"
\`\`\`

### File Upload Issues

#### "File too large" errors
\`\`\`bash
# Check nginx client_max_body_size
grep client_max_body_size /etc/nginx/sites-available/visionvideoke

# Increase if needed
sudo nano /etc/nginx/sites-available/visionvideoke
# Add: client_max_body_size 100M;

sudo nginx -t && sudo systemctl reload nginx
\`\`\`

#### Upload directory permissions
\`\`\`bash
# Check upload directory permissions
ls -la /var/www/visionvideoke/uploads/

# Fix permissions if needed
sudo chown -R ec2-user:ec2-user /var/www/visionvideoke/uploads/
sudo chmod -R 755 /var/www/visionvideoke/uploads/
\`\`\`

## Diagnostic Commands

### System Health Check
\`\`\`bash
#!/bin/bash
echo "=== System Health Check ==="
echo "Date: \$(date)"
echo ""

echo "=== System Resources ==="
echo "CPU Usage:"
top -bn1 | grep "Cpu(s)"
echo ""
echo "Memory Usage:"
free -h
echo ""
echo "Disk Usage:"
df -h
echo ""

echo "=== Services Status ==="
echo "PM2 Status:"
pm2 status
echo ""
echo "Nginx Status:"
sudo systemctl status nginx --no-pager -l
echo ""

echo "=== Network Connectivity ==="
echo "Port 3000 (Application):"
sudo netstat -tlnp | grep :3000
echo ""
echo "Port 80 (HTTP):"
sudo netstat -tlnp | grep :80
echo ""
echo "Port 443 (HTTPS):"
sudo netstat -tlnp | grep :443
echo ""

echo "=== SSL Certificate ==="
sudo certbot certificates 2>/dev/null || echo "No certificates found"
echo ""

echo "=== Recent Errors ==="
echo "Application Errors (last 10 lines):"
tail -n 10 /var/log/visionvideoke/error.log 2>/dev/null || echo "No error log found"
echo ""
echo "Nginx Errors (last 10 lines):"
sudo tail -n 10 /var/log/nginx/error.log 2>/dev/null || echo "No nginx error log found"
\`\`\`

### Log Analysis
\`\`\`bash
# View application logs in real-time
pm2 logs --lines 50

# Search for errors in logs
grep -i error /var/log/visionvideoke/*.log

# Check nginx access patterns
sudo tail -f /var/log/nginx/access.log

# Monitor system messages
sudo tail -f /var/log/messages
\`\`\`

## Getting Help

### Log Collection for Support
\`\`\`bash
# Create support package
mkdir -p /tmp/visionvideoke-support
cp /var/log/visionvideoke/*.log /tmp/visionvideoke-support/ 2>/dev/null || true
sudo cp /var/log/nginx/*.log /tmp/visionvideoke-support/ 2>/dev/null || true
pm2 logs --lines 100 > /tmp/visionvideoke-support/pm2-logs.txt
./status.sh > /tmp/visionvideoke-support/status.txt
tar -czf visionvideoke-support-\$(date +%Y%m%d).tar.gz -C /tmp visionvideoke-support/
\`\`\`

### Contact Information
- Documentation: Check README.md and installation guides
- Logs: Always include relevant log files when reporting issues
- System Info: Include output of \`./status.sh\` when seeking help

### Emergency Recovery
If the system becomes unresponsive:
1. Reboot the EC2 instance
2. Check system logs: \`sudo tail -f /var/log/messages\`
3. Restart all services: \`./restart-all.sh\`
4. Restore from backup if needed: \`./restore-backup.sh\`
EOF

    log "Documentation created successfully"
}

# Function to create customer delivery package
create_delivery_package() {
    log "Creating customer delivery package..."
    
    # Create distribution directory
    rm -rf $DIST_DIR
    mkdir -p $DIST_DIR
    
    # Create final package
    cd $(dirname $BUILD_DIR)
    tar -czf $DIST_DIR/${PACKAGE_NAME}-${VERSION}.tar.gz \
        -C $BUILD_DIR \
        --transform "s,^,${PACKAGE_NAME}-${VERSION}/," \
        .
    
    # Create checksums
    cd $DIST_DIR
    sha256sum ${PACKAGE_NAME}-${VERSION}.tar.gz > ${PACKAGE_NAME}-${VERSION}.sha256
    
    # Create package info
    cat > ${PACKAGE_NAME}-${VERSION}.info <<EOF
Package: ${PACKAGE_NAME}
Version: ${VERSION}
Build Date: $(date)
Build Host: $(hostname)
Size: $(du -h ${PACKAGE_NAME}-${VERSION}.tar.gz | cut -f1)
SHA256: $(cat ${PACKAGE_NAME}-${VERSION}.sha256 | cut -d' ' -f1)

Description:
Complete installation package for Vision Videoke platform on Amazon Linux EC2.
Includes one-click installer, configuration scripts, and documentation.

Requirements:
- Amazon Linux 2 EC2 instance
- Minimum t3.medium (2 vCPUs, 4GB RAM)
- 20GB+ storage
- Domain name with DNS configured

Installation:
1. Upload package to EC2 instance
2. Extract: tar -xzf ${PACKAGE_NAME}-${VERSION}.tar.gz
3. Run: cd ${PACKAGE_NAME}-${VERSION} && ./customer-installer.sh

Support:
- Complete documentation included in docs/ directory
- Troubleshooting guide available
- Management scripts provided
EOF
    
    log "Customer delivery package created: $DIST_DIR/${PACKAGE_NAME}-${VERSION}.tar.gz"
}

# Function to create installer variants
create_installer_variants() {
    log "Creating installer variants..."
    
    # Create minimal installer (without application package)
    cp $BUILD_DIR/customer-installer.sh $DIST_DIR/minimal-installer.sh
    
    # Create advanced installer with more options
    cat > $DIST_DIR/advanced-installer.sh <<'EOF'
#!/bin/bash
# Vision Videoke Advanced Installer
# Includes additional configuration options

# Source the main installer
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -f "$SCRIPT_DIR/customer-installer.sh" ]; then
    source "$SCRIPT_DIR/customer-installer.sh"
else
    echo "Error: customer-installer.sh not found"
    exit 1
fi

# Additional advanced configuration options
advanced_config() {
    echo "=== Advanced Configuration ==="
    
    # Database configuration
    read -p "Configure PostgreSQL database? (y/N): " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        setup_postgresql
    fi
    
    # Redis configuration
    read -p "Configure Redis cache? (y/N): " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        setup_redis
    fi
    
    # CloudWatch monitoring
    read -p "Configure CloudWatch monitoring? (y/N): " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        setup_cloudwatch
    fi
}

# Override main function to include advanced config
main() {
    welcome_message
    check_system
    collect_info
    advanced_config
    download_installer
    run_system_setup
    setup_security
    setup_directories
    setup_nginx
    create_environment
    install_application
    setup_ssl
    setup_monitoring
    create_management_scripts
    final_setup
    show_success
}
EOF
    
    chmod +x $DIST_DIR/advanced-installer.sh
    chmod +x $DIST_DIR/minimal-installer.sh
    
    log "Installer variants created"
}

# Function to create distribution manifest
create_manifest() {
    log "Creating distribution manifest..."
    
    cat > $DIST_DIR/MANIFEST.txt <<EOF
Vision Videoke EC2 Distribution Package
======================================

Package: ${PACKAGE_NAME}-${VERSION}
Build Date: $(date)
Build Version: ${VERSION}

Files Included:
$(ls -la $DIST_DIR/ | tail -n +2)

Package Contents:
- customer-installer.sh: Main one-click installer
- advanced-installer.sh: Advanced installer with additional options
- minimal-installer.sh: Minimal installer without application package
- scripts/: System setup and configuration scripts
- config/: Nginx and system configuration templates
- app/: Vision Videoke application package
- docs/: Complete documentation and guides

Installation Instructions:
1. Upload ${PACKAGE_NAME}-${VERSION}.tar.gz to your EC2 instance
2. Extract: tar -xzf ${PACKAGE_NAME}-${VERSION}.tar.gz
3. Run: cd ${PACKAGE_NAME}-${VERSION} && ./customer-installer.sh

Verification:
SHA256: $(cat ${PACKAGE_NAME}-${VERSION}.sha256 | cut -d' ' -f1)

Support:
- Complete documentation in docs/ directory
- Troubleshooting guide included
- Management scripts provided
- Health monitoring configured

Version History:
- v1.0.0: Initial release with complete EC2 deployment system
EOF
    
    log "Distribution manifest created"
}

# Main function
main() {
    log "Starting Vision Videoke package creation..."
    
    create_package_structure
    copy_scripts
    copy_configs
    prepare_app_package
    create_documentation
    create_delivery_package
    create_installer_variants
    create_manifest
    
    log "Package creation completed successfully!"
    log ""
    log "Distribution files created in: $DIST_DIR"
    log "Main package: ${PACKAGE_NAME}-${VERSION}.tar.gz"
    log "Package size: $(du -h $DIST_DIR/${PACKAGE_NAME}-${VERSION}.tar.gz | cut -f1)"
    log ""
    log "Customer delivery files:"
    ls -la $DIST_DIR/
    log ""
    log "To distribute to customers:"
    log "1. Upload ${PACKAGE_NAME}-${VERSION}.tar.gz to your distribution server"
    log "2. Provide customers with download link and installation instructions"
    log "3. Include the SHA256 checksum for verification"
}

# Run main function
main "$@"

