# YouTube Clone Deployment Guide

## 🚀 Quick Deployment Commands

### Option 1: Automated Deployment (Recommended)
```bash
# Make the deployment script executable
chmod +x deploy.sh

# Run the deployment script
./deploy.sh
```

### Option 2: Manual Step-by-Step

#### 1. Connect to Server & Activate Environment
```bash
# SSH into your server
ssh fnkjyinw@your-server-ip

# Activate virtual environment
source /home/fnkjyinw/virtualenv/youtube/2.7/bin/activate

# Navigate to project directory
cd /home/fnkjyinw/youtube
```

#### 2. Install Dependencies
```bash
# Install Python packages
pip install -r requirements.txt

# Install additional production packages
pip install gunicorn psycopg2-binary
```

#### 3. Configure Django Settings
```bash
# Create production settings file (optional)
cp youtube_project/settings.py youtube_project/settings_production.py

# Edit settings for production
nano youtube_project/settings_production.py
```

#### 4. Database Setup
```bash
# Run migrations
python manage.py migrate

# Create superuser if needed
python manage.py createsuperuser

# Collect static files
python manage.py collectstatic --noinput
```

#### 5. Set File Permissions
```bash
# Set proper permissions
chmod -R 755 /home/fnkjyinw/youtube
chmod -R 777 /home/fnkjyinw/youtube/static
chmod -R 777 /home/fnkjyinw/youtube/media
```

#### 6. Start Web Server
```bash
# Start with Gunicorn (recommended for production)
gunicorn --workers 3 --bind 127.0.0.1:8000 youtube_project.wsgi:application --daemon

# Or start in foreground for testing
gunicorn --workers 3 --bind 127.0.0.1:8000 youtube_project.wsgi:application
```

## 🔧 Server Configuration

### Systemd Service (Auto-start on boot)
```bash
# Copy service file
sudo cp youtube.service /etc/systemd/system/

# Reload systemd
sudo systemctl daemon-reload

# Enable service (start on boot)
sudo systemctl enable youtube.service

# Start service
sudo systemctl start youtube.service

# Check status
sudo systemctl status youtube.service

# View logs
sudo journalctl -u youtube.service -f
```

### Nginx Configuration
```bash
# Copy Nginx config
sudo cp nginx-youtube.conf /etc/nginx/sites-available/youtube

# Enable site
sudo ln -s /etc/nginx/sites-available/youtube /etc/nginx/sites-enabled/

# Test Nginx config
sudo nginx -t

# Restart Nginx
sudo systemctl restart nginx
```

## 🌐 Domain & SSL Setup

### Domain Configuration
1. **Point DNS**: A record `your-domain.com` → `your-server-ip`
2. **Subdomain**: Optional `www.your-domain.com` → `your-server-ip`
3. **Propagation**: Wait 24-48 hours for DNS propagation

### SSL Certificate (Let's Encrypt)
```bash
# Install Certbot
sudo apt update
sudo apt install certbot python3-certbot-nginx

# Get SSL certificate
sudo certbot --nginx -d your-domain.com -d www.your-domain.com

# Auto-renew SSL
sudo crontab -e
# Add: 0 12 * * * /usr/bin/certbot renew --quiet
```

## 📊 Monitoring & Logs

### View Application Logs
```bash
# Gunicorn logs
tail -f /var/log/gunicorn.log

# Nginx logs
sudo tail -f /var/log/nginx/error.log

# Django logs
tail -f /home/fnkjyinw/youtube/django.log
```

### Monitor Server Performance
```bash
# System resources
htop
df -h
free -m

# Network connections
netstat -tulpn | grep :8000

# Process status
ps aux | grep gunicorn
```

## 🔒 Security Recommendations

### Firewall Setup
```bash
# Allow HTTP/HTTPS
sudo ufw allow 80
sudo ufw allow 443
sudo ufw allow 22

# Allow Gunicorn port (internal)
sudo ufw allow from 127.0.0.1 to any port 8000
```

### Django Security Settings
```python
# In settings_production.py
DEBUG = False
ALLOWED_HOSTS = ['your-domain.com', 'www.your-domain.com']
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
```

## 🚨 Troubleshooting

### Common Issues & Solutions

#### 502 Bad Gateway
```bash
# Check if Gunicorn is running
ps aux | grep gunicorn

# Restart Gunicorn
pkill -f gunicorn
gunicorn --workers 3 --bind 127.0.0.1:8000 youtube_project.wsgi:application --daemon
```

#### Static Files 404
```bash
# Check permissions
ls -la /home/fnkjyinw/youtube/static/

# Fix permissions
chmod -R 777 /home/fnkjyinw/youtube/static
```

#### Database Connection Error
```bash
# Check PostgreSQL status
sudo systemctl status postgresql

# Test connection
python manage.py dbshell
```

#### Permission Denied
```bash
# Check file ownership
ls -la /home/fnkjyinw/youtube/

# Fix ownership
sudo chown -R fnkjyinw:fnkjyinw /home/fnkjyinw/youtube
```

## 📱 Performance Optimization

### Database Optimization
```sql
-- Create indexes for better performance
CREATE INDEX CONCURRENTLY IF NOT EXISTS videos_video_upload_date_idx ON videos_video(upload_date);
CREATE INDEX CONCURRENTLY IF NOT EXISTS videos_video_uploader_idx ON videos_video(uploader_id);
```

### Caching Setup
```python
# In settings.py
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        }
    }
}
```

## 🔄 Backup Strategy

### Automated Backups
```bash
# Create backup script
cat > backup.sh << 'EOF'
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/home/fnkjyinw/backups"

# Database backup
pg_dump youtube_db > $BACKUP_DIR/youtube_db_$DATE.sql

# Media files backup
tar -czf $BACKUP_DIR/media_$DATE.tar.gz /home/fnkjyinw/youtube/media/

# Keep only last 7 days
find $BACKUP_DIR -name "*.sql" -mtime +7 -delete
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete
EOF

# Make executable and schedule
chmod +x backup.sh
crontab -e
# Add: 0 2 * * * /home/fnkjyinw/backup.sh
```

## 📞 Support & Maintenance

### Regular Maintenance Tasks
- **Weekly**: Update packages, check logs, monitor disk space
- **Monthly**: Review security logs, update SSL certificates
- **Quarterly**: Performance optimization, database cleanup

### Emergency Contacts
- **Server Provider**: For hardware/network issues
- **Domain Registrar**: For DNS problems
- **SSL Provider**: For certificate issues

## 🎉 Post-Deployment Checklist

### ✅ Immediate Tests
- [ ] Homepage loads correctly
- [ ] Video upload works
- [ ] Video playback functions
- [ ] User registration/login works
- [ ] Mobile responsiveness OK

### ✅ Performance Tests
- [ ] Page load time < 3 seconds
- [ ] Video streaming smooth
- [ ] No console errors
- [ ] Memory usage < 80%

### ✅ Security Checks
- [ ] HTTPS working properly
- [ ] No security headers missing
- [ ] File permissions correct
- [ ] Firewall rules active

---

## 🆘 Need Help?

For deployment issues, check:
1. **Server logs** in `/var/log/`
2. **Django debug mode**: Set `DEBUG = True` temporarily
3. **Network connectivity**: `telnet your-domain.com 80`
4. **Process status**: `ps aux | grep gunicorn`

**Deployment completed! Your YouTube Clone should now be live!** 🚀
