# Linux Server Deployment Guide

## 🐧 Complete Guide to Deploy Al Mirag Poultry Management on Linux

This guide ensures your application runs smoothly on any Linux server with optimal performance and security.

## ✅ What's Been Optimized for Linux

### **1. Enhanced WSGI Configuration**
- ✅ Production-ready logging
- ✅ Proper error handling
- ✅ Database initialization
- ✅ Environment variable setup

### **2. Linux-Specific App Configuration**
- ✅ Proper file permissions (755/644)
- ✅ Database path optimization
- ✅ Upload folder security
- ✅ File size limits

### **3. Enhanced .htaccess**
- ✅ Increased process limits (LSAPI_CHILDREN=15)
- ✅ Security headers
- ✅ Performance optimizations
- ✅ File access restrictions

### **4. Database Optimization**
- ✅ Instance folder structure
- ✅ SQLite threading support
- ✅ Connection pooling
- ✅ Backup configuration

## 🚀 Quick Start

### **Option 1: Automated Deployment**
```bash
# Make scripts executable
chmod +x *.sh

# Install dependencies
./install_dependencies.sh

# Deploy application
./deploy_linux.sh

# Start application
./start_linux.sh
```

### **Option 2: Manual Setup**
```bash
# 1. Install Python dependencies
pip3 install -r requirements.txt

# 2. Set permissions
chmod 755 .
chmod 644 *.py
chmod 777 uploads/
chmod 755 instance/

# 3. Start application
python3 app.py
```

## 📋 System Requirements

### **Minimum Requirements**
- **OS:** Ubuntu 18.04+, CentOS 7+, Debian 9+
- **RAM:** 512MB minimum, 1GB recommended
- **Storage:** 1GB free space
- **Python:** 3.7 or higher
- **Web Server:** Apache 2.4+ or Nginx 1.18+

### **Recommended Requirements**
- **OS:** Ubuntu 20.04+ or CentOS 8+
- **RAM:** 2GB or more
- **Storage:** 5GB free space
- **Python:** 3.8 or higher
- **Web Server:** Apache 2.4+ with mod_wsgi

## 🔧 Web Server Configuration

### **Apache Configuration**

#### **1. Enable Required Modules**
```bash
sudo a2enmod wsgi
sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires
sudo a2enmod deflate
sudo systemctl restart apache2
```

#### **2. Virtual Host Configuration**
Create `/etc/apache2/sites-available/poultry-app.conf`:
```apache
<VirtualHost *:80>
    ServerName yourdomain.com
    DocumentRoot /path/to/your/app
    
    WSGIDaemonProcess poultry-app python-path=/path/to/your/app
    WSGIProcessGroup poultry-app
    WSGIScriptAlias / /path/to/your/app/passenger_wsgi.py
    
    <Directory /path/to/your/app>
        WSGIApplicationGroup %{GLOBAL}
        Require all granted
    </Directory>
    
    # Static files
    Alias /static /path/to/your/app/static
    <Directory /path/to/your/app/static>
        Require all granted
    </Directory>
    
    # Security
    <Directory /path/to/your/app/instance>
        Require all denied
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/poultry-app_error.log
    CustomLog ${APACHE_LOG_DIR}/poultry-app_access.log combined
</VirtualHost>
```

#### **3. Enable Site**
```bash
sudo a2ensite poultry-app
sudo systemctl reload apache2
```

### **Nginx Configuration**

#### **1. Install Nginx and uWSGI**
```bash
sudo apt-get install nginx uwsgi uwsgi-plugin-python3
```

#### **2. Nginx Configuration**
Create `/etc/nginx/sites-available/poultry-app`:
```nginx
server {
    listen 80;
    server_name yourdomain.com;
    
    location / {
        include uwsgi_params;
        uwsgi_pass unix:/tmp/poultry-app.sock;
    }
    
    location /static {
        alias /path/to/your/app/static;
        expires 1M;
        add_header Cache-Control "public, immutable";
    }
    
    location /uploads {
        alias /path/to/your/app/uploads;
        expires 1M;
    }
}
```

#### **3. uWSGI Configuration**
Create `/etc/uwsgi/apps-available/poultry-app.ini`:
```ini
[uwsgi]
module = passenger_wsgi:application
master = true
processes = 4
socket = /tmp/poultry-app.sock
chmod-socket = 666
vacuum = true
die-on-term = true
pythonpath = /path/to/your/app
```

## 🔒 Security Configuration

### **1. Firewall Setup**
```bash
# Ubuntu/Debian
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

# CentOS/RHEL
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
```

### **2. SSL Certificate (Let's Encrypt)**
```bash
# Install Certbot
sudo apt-get install certbot python3-certbot-apache

# Get certificate
sudo certbot --apache -d yourdomain.com

# Auto-renewal
sudo crontab -e
# Add: 0 12 * * * /usr/bin/certbot renew --quiet
```

### **3. File Permissions**
```bash
# Set proper permissions
find /path/to/your/app -type f -name "*.py" -exec chmod 644 {} \;
find /path/to/your/app -type d -exec chmod 755 {} \;
chmod 777 /path/to/your/app/uploads
chmod 755 /path/to/your/app/instance
```

## 📊 Performance Optimization

### **1. Database Optimization**
```bash
# Regular database maintenance
sqlite3 /path/to/your/app/instance/poultry.db "VACUUM;"
sqlite3 /path/to/your/app/instance/poultry.db "ANALYZE;"
```

### **2. Log Rotation**
```bash
# Install logrotate configuration
sudo cp poultry-app.logrotate /etc/logrotate.d/
```

### **3. System Monitoring**
```bash
# Set up monitoring cron job
crontab -e
# Add: */5 * * * * /path/to/your/app/monitor.sh
```

## 🔄 Backup and Maintenance

### **1. Automated Backups**
```bash
# Set up daily backups
crontab -e
# Add: 0 2 * * * /path/to/your/app/backup.sh
```

### **2. Database Backup**
```bash
# Manual backup
./backup.sh

# Restore from backup
cp /home/backups/poultry/poultry_backup_YYYYMMDD_HHMMSS.db /path/to/your/app/instance/poultry.db
```

### **3. Application Updates**
```bash
# Update application
git pull origin main
pip3 install -r requirements.txt
sudo systemctl restart apache2  # or nginx
```

## 🐛 Troubleshooting

### **Common Issues**

#### **1. Permission Denied**
```bash
# Fix file permissions
sudo chown -R www-data:www-data /path/to/your/app
chmod -R 755 /path/to/your/app
chmod 777 /path/to/your/app/uploads
```

#### **2. Database Locked**
```bash
# Check for running processes
ps aux | grep python
# Kill stuck processes
sudo pkill -f "python.*app.py"
```

#### **3. Module Not Found**
```bash
# Check Python path
python3 -c "import sys; print(sys.path)"
# Install missing dependencies
pip3 install -r requirements.txt
```

#### **4. Service Won't Start**
```bash
# Check logs
sudo journalctl -u apache2 -f
tail -f /var/log/apache2/error.log
tail -f /path/to/your/app/logs/app.log
```

### **Performance Issues**

#### **1. High Memory Usage**
```bash
# Monitor memory
htop
# Optimize Apache/Nginx configuration
# Reduce LSAPI_CHILDREN in .htaccess
```

#### **2. Slow Database Queries**
```bash
# Check database size
ls -lh /path/to/your/app/instance/poultry.db
# Optimize database
sqlite3 /path/to/your/app/instance/poultry.db "VACUUM; ANALYZE;"
```

## 📈 Monitoring and Logs

### **1. Application Logs**
```bash
# View application logs
tail -f /path/to/your/app/logs/app.log

# View system logs
sudo journalctl -u apache2 -f
```

### **2. Performance Monitoring**
```bash
# System resources
htop
iostat -x 1
df -h

# Application monitoring
./monitor.sh
```

### **3. Error Tracking**
```bash
# Check error logs
grep -i error /path/to/your/app/logs/app.log
grep -i error /var/log/apache2/error.log
```

## 🎯 Production Checklist

### **Before Going Live:**
- [ ] SSL certificate installed
- [ ] Firewall configured
- [ ] File permissions set correctly
- [ ] Database backed up
- [ ] Monitoring set up
- [ ] Log rotation configured
- [ ] Backup system tested

### **After Deployment:**
- [ ] Test all functionality
- [ ] Monitor performance
- [ ] Check error logs
- [ ] Verify backups
- [ ] Test SSL certificate
- [ ] Monitor resource usage

## 🆘 Support

### **Getting Help:**
1. Check application logs: `/path/to/your/app/logs/app.log`
2. Check system logs: `sudo journalctl -u apache2`
3. Run diagnostics: `./deploy_linux.sh`
4. Check file permissions: `ls -la /path/to/your/app`

### **Emergency Recovery:**
```bash
# Stop application
sudo systemctl stop apache2

# Restore from backup
./backup.sh restore

# Restart services
sudo systemctl start apache2
```

---

**Your Al Mirag Poultry Management app is now optimized for Linux servers!** 🎉

The application will run smoothly with proper performance, security, and reliability on any Linux distribution.
