diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md new file mode 100644 index 0000000..ae29d33 --- /dev/null +++ b/DEPLOYMENT.md @@ -0,0 +1,509 @@ +# Deployment Guide for AI-Agent-Platform + +## Overview + +This guide provides comprehensive instructions for deploying the AI-Agent-Platform to a Hostinger VPS using the automated deployment scripts. + +## Prerequisites + +### Server Requirements +- Ubuntu 20.04 LTS or later (or Debian-based Linux) +- Minimum 1GB RAM +- At least 10GB free disk space +- Root access (sudo privileges) +- Domain name pointing to your server IP + +### Before You Begin +1. **DNS Configuration**: Ensure your domain's A record points to your VPS IP address +2. **SSH Access**: Verify you can SSH into your VPS +3. **Email Address**: Have an email ready for SSL certificate notifications + +## Deployment Scripts + +### 1. Final Deployment Script (`final-deploy.sh`) + +The comprehensive, fully automated deployment script for Hostinger VPS. + +#### Features +- **Complete VPS Setup**: Installs and configures all required packages +- **Nginx Configuration**: Sets up web server with security headers +- **SSL Automation**: Installs and auto-renews Let's Encrypt certificates +- **Backup System**: Daily backups with 30-day retention +- **Monitoring**: Real-time status monitoring every 15 minutes +- **Security**: Firewall configuration and security best practices +- **Logging**: Comprehensive logging for all operations + +#### Deployment Information +- **User**: wasalstor-web +- **Timestamp**: 2025-10-20 04:00:22 +- **Target Platform**: Hostinger VPS +- **Web Server**: Nginx +- **SSL Provider**: Let's Encrypt (Certbot) + +#### Usage + +```bash +# 1. Transfer the script to your VPS +scp final-deploy.sh user@your-server-ip:/home/user/ + +# 2. SSH into your VPS +ssh user@your-server-ip + +# 3. Make the script executable (if not already) +chmod +x final-deploy.sh + +# 4. Run the deployment script as root +sudo ./final-deploy.sh +``` + +#### Interactive Prompts + +The script will ask for: +1. **Domain Name**: Your website domain (e.g., example.com) +2. **Email Address**: For SSL certificate notifications + +Example: +``` +Enter your domain name (e.g., example.com): yoursite.com +Enter your email for SSL notifications: admin@yoursite.com +``` + +#### Deployment Process + +The script performs these steps in order: + +1. **Directory Creation** + - `/var/www/AI-Agent-Platform` - Web root + - `/var/backups/AI-Agent-Platform` - Backup storage + - `/var/log/AI-Agent-Platform` - Log files + +2. **Package Installation** + - Nginx web server + - Certbot for SSL + - Git for version control + - Security tools (UFW, Fail2ban) + - System utilities + +3. **Firewall Configuration** + - Enable UFW firewall + - Allow ports: 22 (SSH), 80 (HTTP), 443 (HTTPS) + - Apply security rules + +4. **Nginx Setup** + - Create server configuration + - Enable gzip compression + - Add security headers + - Configure caching for static files + +5. **SSL Certificate** + - Request certificate from Let's Encrypt + - Configure for domain and www subdomain + - Enable HTTPS redirect + +6. **SSL Auto-Renewal** + - Set up cron job (runs twice daily) + - Automatic nginx reload after renewal + - Logging of renewal attempts + +7. **Backup System** + - Create backup script + - Schedule daily backups (2 AM) + - 30-day retention policy + - Compressed tar.gz archives + +8. **Monitoring Setup** + - Create monitoring script + - Check Nginx status + - Monitor SSL certificate expiry + - Track disk usage + - Verify website accessibility + - Status JSON output every 15 minutes + +9. **Health Check** + - Verify all services running + - Check SSL certificate validity + - Confirm disk space availability + - Count available backups + +10. **Deployment Report** + - Generate comprehensive report + - Document all configurations + - List automated tasks + - Provide next steps + +#### Directory Structure After Deployment + +``` +/var/www/AI-Agent-Platform/ # Web root (deploy your files here) +/var/backups/AI-Agent-Platform/ # Backup storage + └── backup_YYYYMMDD_HHMMSS.tar.gz +/var/log/AI-Agent-Platform/ # Log directory + ├── deployment_YYYYMMDD_HHMMSS.log + ├── deployment_report_YYYYMMDD_HHMMSS.txt + ├── nginx_access.log + ├── nginx_error.log + ├── backup_cron.log + ├── monitoring.log + ├── ssl_renewal.log + └── status.json +/etc/nginx/sites-available/AI-Agent-Platform # Nginx config +/etc/nginx/sites-enabled/AI-Agent-Platform # Enabled site +/usr/local/bin/AI-Agent-Platform-backup.sh # Backup script +/usr/local/bin/AI-Agent-Platform-monitor.sh # Monitoring script +``` + +#### Automated Tasks + +##### SSL Renewal +- **Schedule**: Twice daily (midnight and noon) +- **Command**: `certbot renew --quiet --post-hook 'systemctl reload nginx'` +- **Log**: `/var/log/AI-Agent-Platform/ssl_renewal.log` + +##### Daily Backups +- **Schedule**: Daily at 2:00 AM +- **Retention**: 30 days +- **Format**: Compressed tar.gz +- **Location**: `/var/backups/AI-Agent-Platform/` +- **Log**: `/var/log/AI-Agent-Platform/backup_cron.log` + +##### Status Monitoring +- **Schedule**: Every 15 minutes +- **Checks**: + - Nginx service status + - SSL certificate expiry + - Disk usage + - Website HTTP response + - Overall health status +- **Output**: `/var/log/AI-Agent-Platform/status.json` +- **Log**: `/var/log/AI-Agent-Platform/monitoring.log` + +#### Status Monitoring JSON + +The monitoring system creates a JSON file with real-time status: + +```json +{ + "timestamp": "2025-10-20T04:00:22+00:00", + "nginx_status": "active", + "ssl_expiry": "Mar 20 04:00:22 2026 GMT", + "ssl_days_left": 151, + "disk_usage_percent": 45, + "http_status": 200, + "deployment_healthy": true +} +``` + +#### Post-Deployment Steps + +1. **Deploy Your Application** + ```bash + # Transfer your files to the web root + sudo rsync -av /path/to/your/files/ /var/www/AI-Agent-Platform/ + + # Set proper permissions + sudo chown -R www-data:www-data /var/www/AI-Agent-Platform/ + sudo chmod -R 755 /var/www/AI-Agent-Platform/ + ``` + +2. **Verify Deployment** + ```bash + # Check Nginx status + sudo systemctl status nginx + + # Check SSL certificate + sudo certbot certificates + + # Test website access + curl -I https://yoursite.com + ``` + +3. **Monitor Status** + ```bash + # View real-time status + cat /var/log/AI-Agent-Platform/status.json + + # Check monitoring logs + tail -f /var/log/AI-Agent-Platform/monitoring.log + + # View nginx access logs + tail -f /var/log/AI-Agent-Platform/nginx_access.log + ``` + +4. **Verify Automated Tasks** + ```bash + # List cron jobs + sudo crontab -l + + # Manually trigger backup + sudo /usr/local/bin/AI-Agent-Platform-backup.sh + + # Manually run monitoring + sudo /usr/local/bin/AI-Agent-Platform-monitor.sh + ``` + +### 2. Smart Deploy Script (`smart-deploy.sh`) + +Interactive deployment menu in Arabic with manual control options. + +#### Features +- Arabic language interface +- Step-by-step deployment control +- Manual intervention options +- Status checking capabilities + +#### Usage +```bash +./smart-deploy.sh +``` + +#### Menu Options +1. التحقق من حالة النشر (Check deployment status) +2. نشر تلقائي باستخدام git pull (Auto deploy with git pull) +3. إعداد شهادة SSL باستخدام certbot (SSL setup with certbot) +4. تكوين webhooks على GitHub (Configure GitHub webhooks) +5. تكوين nginx (Configure nginx) +6. نظام النسخ الاحتياطي (Backup system) +7. مراقبة السجلات (Log monitoring) +8. فحص الأداء (Performance check) +9. فحص الأمان (Security scan) +10. العودة (Rollback) + +## Troubleshooting + +### Common Issues + +#### Port 80/443 Already in Use +```bash +# Check what's using the ports +sudo netstat -tulpn | grep :80 +sudo netstat -tulpn | grep :443 + +# Stop conflicting service (e.g., Apache) +sudo systemctl stop apache2 +sudo systemctl disable apache2 +``` + +#### SSL Certificate Failure +```bash +# Check DNS resolution +nslookup yoursite.com + +# Test certbot dry-run +sudo certbot certbot --nginx -d yoursite.com --dry-run + +# Check nginx configuration +sudo nginx -t +``` + +#### Nginx Won't Start +```bash +# Check configuration syntax +sudo nginx -t + +# View error logs +sudo tail -f /var/log/nginx/error.log +sudo tail -f /var/log/AI-Agent-Platform/nginx_error.log + +# Check port availability +sudo netstat -tulpn | grep :80 +``` + +#### Backup Not Running +```bash +# Check cron logs +sudo grep CRON /var/log/syslog + +# Test backup script manually +sudo /usr/local/bin/AI-Agent-Platform-backup.sh + +# Verify cron job exists +sudo crontab -l | grep backup +``` + +#### Disk Space Issues +```bash +# Check disk usage +df -h + +# Find large files +sudo du -sh /var/* | sort -hr | head -10 + +# Clean old backups manually +sudo find /var/backups/AI-Agent-Platform/ -name "backup_*.tar.gz" -mtime +30 -delete +``` + +### Log Files for Debugging + +```bash +# Deployment log +sudo tail -f /var/log/AI-Agent-Platform/deployment_*.log + +# Nginx access log +sudo tail -f /var/log/AI-Agent-Platform/nginx_access.log + +# Nginx error log +sudo tail -f /var/log/AI-Agent-Platform/nginx_error.log + +# System log +sudo tail -f /var/log/syslog + +# Certbot log +sudo tail -f /var/log/letsencrypt/letsencrypt.log +``` + +## Maintenance + +### Regular Tasks + +#### Check System Health +```bash +# View current status +cat /var/log/AI-Agent-Platform/status.json + +# Check all services +sudo systemctl status nginx +sudo ufw status +``` + +#### Manual Backup +```bash +sudo /usr/local/bin/AI-Agent-Platform-backup.sh +``` + +#### Update SSL Certificate +```bash +sudo certbot renew +sudo systemctl reload nginx +``` + +#### View Logs +```bash +# All deployment logs +ls -lh /var/log/AI-Agent-Platform/ + +# Recent monitoring entries +tail -50 /var/log/AI-Agent-Platform/monitoring.log + +# Recent backups +ls -lh /var/backups/AI-Agent-Platform/ +``` + +### Updating Your Application + +```bash +# 1. Create a backup first +sudo /usr/local/bin/AI-Agent-Platform-backup.sh + +# 2. Deploy new files +sudo rsync -av /path/to/new/files/ /var/www/AI-Agent-Platform/ + +# 3. Set permissions +sudo chown -R www-data:www-data /var/www/AI-Agent-Platform/ + +# 4. Test nginx configuration +sudo nginx -t + +# 5. Reload nginx +sudo systemctl reload nginx + +# 6. Verify deployment +curl -I https://yoursite.com +``` + +### Rollback Procedure + +If deployment fails, restore from backup: + +```bash +# 1. Stop nginx +sudo systemctl stop nginx + +# 2. List available backups +ls -lh /var/backups/AI-Agent-Platform/ + +# 3. Restore from backup +sudo tar -xzf /var/backups/AI-Agent-Platform/backup_YYYYMMDD_HHMMSS.tar.gz -C /var/www/AI-Agent-Platform/ + +# 4. Set permissions +sudo chown -R www-data:www-data /var/www/AI-Agent-Platform/ + +# 5. Start nginx +sudo systemctl start nginx + +# 6. Verify +curl -I https://yoursite.com +``` + +## Security Best Practices + +### After Deployment + +1. **Change SSH Port** (optional but recommended) + ```bash + sudo nano /etc/ssh/sshd_config + # Change Port 22 to another port + sudo systemctl restart sshd + ``` + +2. **Disable Root Login** + ```bash + sudo nano /etc/ssh/sshd_config + # Set: PermitRootLogin no + sudo systemctl restart sshd + ``` + +3. **Configure Fail2ban** + ```bash + sudo systemctl enable fail2ban + sudo systemctl start fail2ban + ``` + +4. **Regular Updates** + ```bash + sudo apt update + sudo apt upgrade -y + ``` + +5. **Monitor Logs** + ```bash + # Set up log rotation if needed + sudo nano /etc/logrotate.d/ai-agent-platform + ``` + +## Support + +### Getting Help + +- Review deployment logs: `/var/log/AI-Agent-Platform/deployment_*.log` +- Check deployment report: `/var/log/AI-Agent-Platform/deployment_report_*.txt` +- Monitor real-time status: `/var/log/AI-Agent-Platform/status.json` + +### Useful Commands + +```bash +# Service management +sudo systemctl status nginx +sudo systemctl restart nginx +sudo systemctl reload nginx + +# Certificate management +sudo certbot certificates +sudo certbot renew --dry-run + +# Firewall management +sudo ufw status verbose +sudo ufw app list + +# Monitoring +cat /var/log/AI-Agent-Platform/status.json | python3 -m json.tool +tail -f /var/log/AI-Agent-Platform/monitoring.log + +# Backups +ls -lh /var/backups/AI-Agent-Platform/ +``` + +## Conclusion + +The final-deploy.sh script provides a complete, production-ready deployment solution for the AI-Agent-Platform on Hostinger VPS. With automated SSL renewal, daily backups, and continuous monitoring, your deployment will be secure, reliable, and easy to maintain. + +For additional customization or advanced configurations, edit the script or Nginx configuration files as needed. diff --git a/QUICK_REFERENCE.md b/QUICK_REFERENCE.md new file mode 100644 index 0000000..e9d82fa --- /dev/null +++ b/QUICK_REFERENCE.md @@ -0,0 +1,204 @@ +# Quick Deployment Reference + +## Main Deployment Command + +```bash +sudo ./final-deploy.sh +``` + +## Pre-Deployment Checklist + +- [ ] Server running Ubuntu 20.04+ or Debian-based Linux +- [ ] Root/sudo access available +- [ ] Domain name configured (A record pointing to server IP) +- [ ] Email address ready for SSL notifications +- [ ] Minimum 1GB RAM and 10GB disk space available + +## Deployment Components + +### 1. User & Timestamp +- **User**: wasalstor-web +- **Timestamp**: 2025-10-20 04:00:22 + +### 2. Automated Features + +#### SSL Certificate (Let's Encrypt) +- Automatic installation via Certbot +- Auto-renewal: Twice daily (midnight and noon) +- Nginx automatically reloaded after renewal +- Logs: `/var/log/AI-Agent-Platform/ssl_renewal.log` + +#### Backup System +- Schedule: Daily at 2:00 AM +- Retention: 30 days +- Format: Compressed tar.gz +- Location: `/var/backups/AI-Agent-Platform/` +- Logs: `/var/log/AI-Agent-Platform/backup_cron.log` + +#### Status Monitoring +- Frequency: Every 15 minutes +- Monitors: Nginx, SSL, Disk, HTTP status +- Output: `/var/log/AI-Agent-Platform/status.json` +- Logs: `/var/log/AI-Agent-Platform/monitoring.log` + +### 3. Directory Structure + +``` +/var/www/AI-Agent-Platform/ # Web root +/var/backups/AI-Agent-Platform/ # Backups +/var/log/AI-Agent-Platform/ # Logs +/etc/nginx/sites-available/ # Nginx config +/usr/local/bin/ # Scripts +``` + +## Post-Deployment + +### Deploy Your Application +```bash +sudo rsync -av /path/to/files/ /var/www/AI-Agent-Platform/ +sudo chown -R www-data:www-data /var/www/AI-Agent-Platform/ +sudo chmod -R 755 /var/www/AI-Agent-Platform/ +``` + +### Check Status +```bash +# View JSON status +cat /var/log/AI-Agent-Platform/status.json + +# Check Nginx +sudo systemctl status nginx + +# Test website +curl -I https://yoursite.com +``` + +### Manual Operations + +#### Trigger Backup +```bash +sudo /usr/local/bin/AI-Agent-Platform-backup.sh +``` + +#### Check Monitoring +```bash +sudo /usr/local/bin/AI-Agent-Platform-monitor.sh +cat /var/log/AI-Agent-Platform/status.json | python3 -m json.tool +``` + +#### Renew SSL +```bash +sudo certbot renew +sudo systemctl reload nginx +``` + +### View Logs +```bash +# Deployment log +sudo tail -f /var/log/AI-Agent-Platform/deployment_*.log + +# Nginx access +sudo tail -f /var/log/AI-Agent-Platform/nginx_access.log + +# Nginx errors +sudo tail -f /var/log/AI-Agent-Platform/nginx_error.log + +# Monitoring +sudo tail -f /var/log/AI-Agent-Platform/monitoring.log + +# Backups +sudo tail -f /var/log/AI-Agent-Platform/backup_cron.log + +# SSL renewal +sudo tail -f /var/log/AI-Agent-Platform/ssl_renewal.log +``` + +## Troubleshooting + +### Nginx Issues +```bash +sudo nginx -t # Test config +sudo systemctl restart nginx # Restart +sudo tail -f /var/log/nginx/error.log +``` + +### SSL Issues +```bash +sudo certbot certificates # List certificates +sudo certbot renew --dry-run # Test renewal +``` + +### Firewall Issues +```bash +sudo ufw status # Check status +sudo ufw allow 80/tcp # Allow HTTP +sudo ufw allow 443/tcp # Allow HTTPS +``` + +### Restore from Backup +```bash +# List backups +ls -lh /var/backups/AI-Agent-Platform/ + +# Stop nginx +sudo systemctl stop nginx + +# Restore +sudo tar -xzf /var/backups/AI-Agent-Platform/backup_YYYYMMDD_HHMMSS.tar.gz \ + -C /var/www/AI-Agent-Platform/ + +# Fix permissions +sudo chown -R www-data:www-data /var/www/AI-Agent-Platform/ + +# Start nginx +sudo systemctl start nginx +``` + +## Monitoring Status JSON Format + +```json +{ + "timestamp": "2025-10-20T04:00:22+00:00", + "nginx_status": "active", + "ssl_expiry": "Mar 20 04:00:22 2026 GMT", + "ssl_days_left": 151, + "disk_usage_percent": 45, + "http_status": 200, + "deployment_healthy": true +} +``` + +## Cron Jobs Configured + +```bash +# SSL renewal (twice daily) +0 0,12 * * * certbot renew --quiet --post-hook 'systemctl reload nginx' + +# Daily backup (2 AM) +0 2 * * * /usr/local/bin/AI-Agent-Platform-backup.sh + +# Status monitoring (every 15 minutes) +*/15 * * * * /usr/local/bin/AI-Agent-Platform-monitor.sh +``` + +## Security Features + +- UFW firewall enabled (ports 22, 80, 443) +- Security headers configured in Nginx +- SSL/TLS encryption with Let's Encrypt +- Fail2ban installed for brute-force protection +- Gzip compression enabled +- Static file caching configured + +## Support Resources + +- Full documentation: `DEPLOYMENT.md` +- Project README: `README.md` +- Deployment report: `/var/log/AI-Agent-Platform/deployment_report_*.txt` +- All logs directory: `/var/log/AI-Agent-Platform/` + +## Alternative Deployment (Smart Deploy) + +For step-by-step interactive deployment in Arabic: +```bash +./smart-deploy.sh +``` diff --git a/README.md b/README.md index 5e633fa..4884b3f 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,89 @@ After finalization, an archive is created in `/tmp/ai-agent-platform-archive-[TI - `--force` - Continue finalization even if warnings are detected - `--no-confirmation` - Skip user confirmation prompt +## Deployment + +The platform includes comprehensive deployment automation for Hostinger VPS. + +### Production Deployment Script (`final-deploy.sh`) + +Full automation script for Hostinger VPS deployment with: + +**Features:** +- ✅ Complete VPS setup and configuration +- ✅ Nginx web server installation and configuration +- ✅ Automatic SSL certificate with Let's Encrypt +- ✅ SSL auto-renewal (twice daily) +- ✅ Automated backup system (daily at 2 AM) +- ✅ Deployment status monitoring (every 15 minutes) +- ✅ Firewall configuration (UFW) +- ✅ Security headers and best practices +- ✅ Comprehensive logging and reporting + +**Configuration:** +- User: wasalstor-web +- Timestamp: 2025-10-20 04:00:22 +- Automated monitoring and maintenance + +**Usage:** +```bash +# Run with sudo (requires root access) +sudo ./final-deploy.sh +``` + +The script will: +1. Install required dependencies (Nginx, Certbot, etc.) +2. Configure firewall rules +3. Set up Nginx with security headers +4. Install SSL certificate from Let's Encrypt +5. Configure automatic SSL renewal +6. Set up daily backup system (30-day retention) +7. Configure status monitoring +8. Generate comprehensive deployment report + +**Automated Tasks:** +- SSL renewal: Runs twice daily (midnight and noon) +- Backups: Daily at 2 AM with 30-day retention +- Monitoring: Status checks every 15 minutes + +**Log Files:** +All logs are stored in `/var/log/AI-Agent-Platform/`: +- `deployment_[timestamp].log` - Deployment process log +- `nginx_access.log` - Nginx access log +- `nginx_error.log` - Nginx error log +- `backup_cron.log` - Backup execution log +- `monitoring.log` - Status monitoring log +- `ssl_renewal.log` - SSL renewal log + +**Status Monitoring:** +Real-time status available at: `/var/log/AI-Agent-Platform/status.json` + +Contains: +- Nginx service status +- SSL certificate expiry +- Disk usage +- HTTP status code +- Overall deployment health + +### Smart Deploy Script (`smart-deploy.sh`) + +Interactive deployment menu in Arabic with options for: +1. Deployment status checking +2. Git pull automation +3. SSL certificate setup +4. GitHub webhooks configuration +5. Nginx configuration +6. Backup system +7. Log monitoring +8. Performance checks +9. Security scanning +10. Rollback capability + +**Usage:** +```bash +./smart-deploy.sh +``` + ## Security and Best Practices Following the platform's security guidelines: @@ -121,6 +204,10 @@ Following the platform's security guidelines: - ✅ Resource cleanup automated - ✅ Comprehensive logging and reporting - ✅ Clear user communication in multiple languages +- ✅ Automated SSL certificate management +- ✅ Security headers configured +- ✅ Firewall rules implemented +- ✅ Regular backups with retention policy ## License diff --git a/final-deploy.sh b/final-deploy.sh new file mode 100755 index 0000000..5589429 --- /dev/null +++ b/final-deploy.sh @@ -0,0 +1,573 @@ +#!/bin/bash + +################################################################################ +# Final Deployment Script for Hostinger VPS +# User: wasalstor-web +# Timestamp: 2025-10-20 04:00:22 +# Full automation for Hostinger VPS setup +################################################################################ + +set -e # Exit on error + +# Color codes for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +CYAN='\033[0;36m' +NC='\033[0m' # No Color + +# Configuration +DEPLOY_USER="wasalstor-web" +DEPLOY_TIMESTAMP="2025-10-20 04:00:22" +PROJECT_NAME="AI-Agent-Platform" +DEPLOY_DIR="/var/www/${PROJECT_NAME}" +BACKUP_DIR="/var/backups/${PROJECT_NAME}" +LOG_DIR="/var/log/${PROJECT_NAME}" +NGINX_CONF="/etc/nginx/sites-available/${PROJECT_NAME}" +NGINX_ENABLED="/etc/nginx/sites-enabled/${PROJECT_NAME}" +DOMAIN="" # To be set during setup +EMAIL="" # To be set during setup + +# Log file +TIMESTAMP=$(date +%Y%m%d_%H%M%S) +LOG_FILE="${LOG_DIR}/deployment_${TIMESTAMP}.log" + +################################################################################ +# Logging Functions +################################################################################ + +log() { + local message="$1" + echo -e "${CYAN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $message" | tee -a "$LOG_FILE" +} + +log_success() { + local message="$1" + echo -e "${GREEN}✓ $message${NC}" | tee -a "$LOG_FILE" +} + +log_error() { + local message="$1" + echo -e "${RED}✗ $message${NC}" | tee -a "$LOG_FILE" +} + +log_warning() { + local message="$1" + echo -e "${YELLOW}⚠ $message${NC}" | tee -a "$LOG_FILE" +} + +log_info() { + local message="$1" + echo -e "${BLUE}ℹ $message${NC}" | tee -a "$LOG_FILE" +} + +################################################################################ +# Utility Functions +################################################################################ + +check_root() { + if [ "$EUID" -ne 0 ]; then + log_error "This script must be run as root (use sudo)" + exit 1 + fi +} + +create_directories() { + log "Creating necessary directories..." + mkdir -p "$DEPLOY_DIR" + mkdir -p "$BACKUP_DIR" + mkdir -p "$LOG_DIR" + chown -R www-data:www-data "$DEPLOY_DIR" + chown -R www-data:www-data "$BACKUP_DIR" + log_success "Directories created" +} + +################################################################################ +# System Update and Package Installation +################################################################################ + +install_dependencies() { + log "Installing required packages..." + + # Update package list + apt-get update -y >> "$LOG_FILE" 2>&1 + + # Install required packages + apt-get install -y \ + nginx \ + certbot \ + python3-certbot-nginx \ + git \ + curl \ + wget \ + rsync \ + cron \ + ufw \ + fail2ban \ + >> "$LOG_FILE" 2>&1 + + log_success "Dependencies installed" +} + +################################################################################ +# Firewall Configuration +################################################################################ + +configure_firewall() { + log "Configuring firewall..." + + # Enable UFW + ufw --force enable >> "$LOG_FILE" 2>&1 + + # Allow SSH, HTTP, and HTTPS + ufw allow 22/tcp >> "$LOG_FILE" 2>&1 + ufw allow 80/tcp >> "$LOG_FILE" 2>&1 + ufw allow 443/tcp >> "$LOG_FILE" 2>&1 + + # Reload UFW + ufw reload >> "$LOG_FILE" 2>&1 + + log_success "Firewall configured" +} + +################################################################################ +# Nginx Configuration +################################################################################ + +configure_nginx() { + log "Configuring Nginx..." + + # Backup existing configuration if it exists + if [ -f "$NGINX_CONF" ]; then + cp "$NGINX_CONF" "${NGINX_CONF}.backup.${TIMESTAMP}" + log_info "Existing Nginx config backed up" + fi + + # Create Nginx configuration + cat > "$NGINX_CONF" << EOF +server { + listen 80; + server_name ${DOMAIN} www.${DOMAIN}; + + root ${DEPLOY_DIR}; + index index.html index.htm; + + # Logging + access_log ${LOG_DIR}/nginx_access.log; + error_log ${LOG_DIR}/nginx_error.log; + + # Security headers + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "no-referrer-when-downgrade" always; + + # Gzip compression + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/javascript application/json; + + location / { + try_files \$uri \$uri/ =404; + } + + # Cache static files + location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ { + expires 1y; + add_header Cache-Control "public, immutable"; + } +} +EOF + + # Enable site + ln -sf "$NGINX_CONF" "$NGINX_ENABLED" + + # Test Nginx configuration + nginx -t >> "$LOG_FILE" 2>&1 + + # Reload Nginx + systemctl reload nginx >> "$LOG_FILE" 2>&1 + + log_success "Nginx configured" +} + +################################################################################ +# SSL Certificate Configuration +################################################################################ + +setup_ssl() { + log "Setting up SSL certificate with Let's Encrypt..." + + # Check if domain is set + if [ -z "$DOMAIN" ]; then + log_error "Domain not set. Skipping SSL setup." + return 1 + fi + + # Check if email is set + if [ -z "$EMAIL" ]; then + log_error "Email not set. Skipping SSL setup." + return 1 + fi + + # Obtain SSL certificate + certbot --nginx \ + -d "$DOMAIN" \ + -d "www.$DOMAIN" \ + --non-interactive \ + --agree-tos \ + --email "$EMAIL" \ + --redirect \ + >> "$LOG_FILE" 2>&1 + + log_success "SSL certificate installed" +} + +################################################################################ +# Automatic SSL Renewal Configuration +################################################################################ + +setup_ssl_renewal() { + log "Configuring automatic SSL renewal..." + + # Test renewal process + certbot renew --dry-run >> "$LOG_FILE" 2>&1 + + # Create renewal cron job (runs twice daily) + CRON_JOB="0 0,12 * * * certbot renew --quiet --post-hook 'systemctl reload nginx' >> ${LOG_DIR}/ssl_renewal.log 2>&1" + + # Check if cron job already exists + if ! crontab -l 2>/dev/null | grep -q "certbot renew"; then + (crontab -l 2>/dev/null; echo "$CRON_JOB") | crontab - + log_success "SSL auto-renewal cron job configured" + else + log_info "SSL auto-renewal cron job already exists" + fi +} + +################################################################################ +# Backup System Configuration +################################################################################ + +setup_backup_system() { + log "Setting up backup system..." + + # Create backup script + BACKUP_SCRIPT="/usr/local/bin/${PROJECT_NAME}-backup.sh" + cat > "$BACKUP_SCRIPT" << 'EOF' +#!/bin/bash + +# Backup Configuration +PROJECT_NAME="AI-Agent-Platform" +DEPLOY_DIR="/var/www/${PROJECT_NAME}" +BACKUP_DIR="/var/backups/${PROJECT_NAME}" +TIMESTAMP=$(date +%Y%m%d_%H%M%S) +BACKUP_FILE="${BACKUP_DIR}/backup_${TIMESTAMP}.tar.gz" +LOG_FILE="/var/log/${PROJECT_NAME}/backup_${TIMESTAMP}.log" +RETENTION_DAYS=30 + +# Create backup +echo "[$(date)] Starting backup..." >> "$LOG_FILE" +tar -czf "$BACKUP_FILE" -C "$DEPLOY_DIR" . >> "$LOG_FILE" 2>&1 + +if [ $? -eq 0 ]; then + echo "[$(date)] Backup created successfully: $BACKUP_FILE" >> "$LOG_FILE" + + # Remove old backups + find "$BACKUP_DIR" -name "backup_*.tar.gz" -type f -mtime +$RETENTION_DAYS -delete + echo "[$(date)] Old backups cleaned (retention: ${RETENTION_DAYS} days)" >> "$LOG_FILE" +else + echo "[$(date)] Backup failed!" >> "$LOG_FILE" + exit 1 +fi +EOF + + chmod +x "$BACKUP_SCRIPT" + + # Create daily backup cron job (runs at 2 AM) + BACKUP_CRON="0 2 * * * $BACKUP_SCRIPT >> ${LOG_DIR}/backup_cron.log 2>&1" + + if ! crontab -l 2>/dev/null | grep -q "${PROJECT_NAME}-backup.sh"; then + (crontab -l 2>/dev/null; echo "$BACKUP_CRON") | crontab - + log_success "Backup system configured (daily at 2 AM, 30-day retention)" + else + log_info "Backup cron job already exists" + fi +} + +################################################################################ +# Deployment Status Monitoring +################################################################################ + +setup_monitoring() { + log "Setting up deployment status monitoring..." + + # Create monitoring script + MONITOR_SCRIPT="/usr/local/bin/${PROJECT_NAME}-monitor.sh" + cat > "$MONITOR_SCRIPT" << 'EOF' +#!/bin/bash + +# Monitoring Configuration +PROJECT_NAME="AI-Agent-Platform" +DOMAIN="${DOMAIN:-localhost}" +LOG_FILE="/var/log/${PROJECT_NAME}/monitoring.log" +STATUS_FILE="/var/log/${PROJECT_NAME}/status.json" + +# Check Nginx status +NGINX_STATUS=$(systemctl is-active nginx) + +# Check SSL certificate expiry (if SSL is configured) +if [ -d "/etc/letsencrypt/live/${DOMAIN}" ]; then + SSL_EXPIRY=$(openssl x509 -enddate -noout -in "/etc/letsencrypt/live/${DOMAIN}/cert.pem" 2>/dev/null | cut -d= -f2) + SSL_DAYS_LEFT=$(( ($(date -d "$SSL_EXPIRY" +%s) - $(date +%s)) / 86400 )) +else + SSL_EXPIRY="N/A" + SSL_DAYS_LEFT="N/A" +fi + +# Check disk usage +DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//') + +# Check website accessibility +HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://${DOMAIN}" 2>/dev/null || echo "000") + +# Create status JSON +cat > "$STATUS_FILE" << EOJ +{ + "timestamp": "$(date -Iseconds)", + "nginx_status": "${NGINX_STATUS}", + "ssl_expiry": "${SSL_EXPIRY}", + "ssl_days_left": ${SSL_DAYS_LEFT}, + "disk_usage_percent": ${DISK_USAGE}, + "http_status": ${HTTP_STATUS}, + "deployment_healthy": $([ "$NGINX_STATUS" = "active" ] && [ "$HTTP_STATUS" = "200" ] && echo "true" || echo "false") +} +EOJ + +# Log status +echo "[$(date)] Status: Nginx=${NGINX_STATUS}, HTTP=${HTTP_STATUS}, Disk=${DISK_USAGE}%, SSL_Days=${SSL_DAYS_LEFT}" >> "$LOG_FILE" + +# Alert if issues detected +if [ "$NGINX_STATUS" != "active" ] || [ "$HTTP_STATUS" != "200" ]; then + echo "[$(date)] ALERT: Service health check failed!" >> "$LOG_FILE" +fi + +if [ "$SSL_DAYS_LEFT" != "N/A" ] && [ "$SSL_DAYS_LEFT" -lt 30 ]; then + echo "[$(date)] WARNING: SSL certificate expires in ${SSL_DAYS_LEFT} days" >> "$LOG_FILE" +fi +EOF + + chmod +x "$MONITOR_SCRIPT" + + # Create monitoring cron job (runs every 15 minutes) + MONITOR_CRON="*/15 * * * * $MONITOR_SCRIPT" + + if ! crontab -l 2>/dev/null | grep -q "${PROJECT_NAME}-monitor.sh"; then + (crontab -l 2>/dev/null; echo "$MONITOR_CRON") | crontab - + log_success "Monitoring system configured (checks every 15 minutes)" + else + log_info "Monitoring cron job already exists" + fi +} + +################################################################################ +# Health Check +################################################################################ + +health_check() { + log "Running health check..." + + # Check Nginx + if systemctl is-active --quiet nginx; then + log_success "Nginx is running" + else + log_error "Nginx is not running" + return 1 + fi + + # Check SSL certificate (if domain is configured) + if [ -n "$DOMAIN" ] && [ -d "/etc/letsencrypt/live/${DOMAIN}" ]; then + SSL_DAYS=$(( ($(date -d "$(openssl x509 -enddate -noout -in "/etc/letsencrypt/live/${DOMAIN}/cert.pem" 2>/dev/null | cut -d= -f2)" +%s) - $(date +%s)) / 86400 )) + log_success "SSL certificate valid for $SSL_DAYS days" + fi + + # Check disk space + DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//') + if [ "$DISK_USAGE" -lt 90 ]; then + log_success "Disk usage: ${DISK_USAGE}%" + else + log_warning "Disk usage high: ${DISK_USAGE}%" + fi + + # Check backup directory + if [ -d "$BACKUP_DIR" ]; then + BACKUP_COUNT=$(find "$BACKUP_DIR" -name "backup_*.tar.gz" -type f | wc -l) + log_success "Backups available: $BACKUP_COUNT" + fi +} + +################################################################################ +# Deployment Report +################################################################################ + +generate_deployment_report() { + log "Generating deployment report..." + + REPORT_FILE="${LOG_DIR}/deployment_report_${TIMESTAMP}.txt" + + cat > "$REPORT_FILE" << EOF +================================================================================ +AI Agent Platform - Deployment Report +================================================================================ + +Deployment Information: +----------------------- +User: ${DEPLOY_USER} +Timestamp: ${DEPLOY_TIMESTAMP} +Execution Time: $(date '+%Y-%m-%d %H:%M:%S') +Project: ${PROJECT_NAME} +Domain: ${DOMAIN:-Not configured} + +Directory Structure: +-------------------- +Deploy Dir: ${DEPLOY_DIR} +Backup Dir: ${BACKUP_DIR} +Log Dir: ${LOG_DIR} +Nginx Config: ${NGINX_CONF} + +System Status: +-------------- +Nginx: $(systemctl is-active nginx) +Certbot: $(command -v certbot &> /dev/null && echo "Installed" || echo "Not installed") +Firewall: $(ufw status | head -1) +Disk Usage: $(df -h / | awk 'NR==2 {print $5}') + +Automated Tasks Configured: +--------------------------- +✓ SSL Auto-renewal (twice daily) +✓ Daily Backups (2 AM, 30-day retention) +✓ Status Monitoring (every 15 minutes) + +SSL Certificate: +---------------- +$(if [ -n "$DOMAIN" ] && [ -d "/etc/letsencrypt/live/${DOMAIN}" ]; then + echo "Status: Configured" + echo "Domain: ${DOMAIN}" + echo "Expiry: $(openssl x509 -enddate -noout -in "/etc/letsencrypt/live/${DOMAIN}/cert.pem" 2>/dev/null | cut -d= -f2)" +else + echo "Status: Not configured" +fi) + +Backup System: +-------------- +Backup Script: /usr/local/bin/${PROJECT_NAME}-backup.sh +Backup Dir: ${BACKUP_DIR} +Schedule: Daily at 2 AM +Retention: 30 days + +Monitoring: +----------- +Monitor Script: /usr/local/bin/${PROJECT_NAME}-monitor.sh +Status File: ${LOG_DIR}/status.json +Schedule: Every 15 minutes + +Log Files: +---------- +Deployment: ${LOG_FILE} +Nginx Access: ${LOG_DIR}/nginx_access.log +Nginx Error: ${LOG_DIR}/nginx_error.log +Backups: ${LOG_DIR}/backup_cron.log +Monitoring: ${LOG_DIR}/monitoring.log +SSL Renewal: ${LOG_DIR}/ssl_renewal.log + +Next Steps: +----------- +1. Deploy your application files to: ${DEPLOY_DIR} +2. Update DNS records to point to this server +3. Monitor status at: ${LOG_DIR}/status.json +4. Check logs regularly in: ${LOG_DIR}/ + +================================================================================ +Deployment completed successfully! +================================================================================ +EOF + + cat "$REPORT_FILE" + log_success "Deployment report saved to: $REPORT_FILE" +} + +################################################################################ +# Main Deployment Process +################################################################################ + +main() { + echo -e "${BLUE}╔══════════════════════════════════════════════════════════╗${NC}" + echo -e "${BLUE}║ AI Agent Platform - Final Deployment Script ║${NC}" + echo -e "${BLUE}║ User: ${DEPLOY_USER} ║${NC}" + echo -e "${BLUE}║ Timestamp: ${DEPLOY_TIMESTAMP} ║${NC}" + echo -e "${BLUE}╚══════════════════════════════════════════════════════════╝${NC}" + echo "" + + # Check root privileges + check_root + + # Get domain and email if not set + if [ -z "$DOMAIN" ]; then + read -p "Enter your domain name (e.g., example.com): " DOMAIN + fi + + if [ -z "$EMAIL" ]; then + read -p "Enter your email for SSL notifications: " EMAIL + fi + + # Create log directory first + mkdir -p "$LOG_DIR" + touch "$LOG_FILE" + + log "Starting deployment process..." + log_info "Deploy User: $DEPLOY_USER" + log_info "Deploy Timestamp: $DEPLOY_TIMESTAMP" + log_info "Domain: $DOMAIN" + + # Step 1: Create directories + create_directories + + # Step 2: Install dependencies + install_dependencies + + # Step 3: Configure firewall + configure_firewall + + # Step 4: Configure Nginx + configure_nginx + + # Step 5: Setup SSL + setup_ssl + + # Step 6: Configure SSL auto-renewal + setup_ssl_renewal + + # Step 7: Setup backup system + setup_backup_system + + # Step 8: Setup monitoring + setup_monitoring + + # Step 9: Health check + health_check + + # Step 10: Generate report + generate_deployment_report + + echo "" + echo -e "${GREEN}╔══════════════════════════════════════════════════════════╗${NC}" + echo -e "${GREEN}║ Deployment Completed Successfully! ║${NC}" + echo -e "${GREEN}╚══════════════════════════════════════════════════════════╝${NC}" + echo "" + log_success "Full deployment completed!" +} + +# Run main function +main "$@"