# Torrent Gateway Installation Guide

This guide covers complete installation and setup of the Torrent Gateway on a fresh server.

## Prerequisites

- Ubuntu/Debian Linux server with root access
- 2GB+ RAM (4GB recommended for transcoding)
- 20GB+ disk space
- Open ports 80, 443 (for web access)
- Optional: Domain name pointed to server IP

## Quick Installation

### Basic Installation (HTTP only)
```bash
sudo ./scripts/install_native.sh
```

### Full Installation with SSL/HTTPS
```bash
sudo ./scripts/install_native.sh --domain gateway.example.com --email admin@example.com
```

### With Monitoring Stack
```bash
sudo ./scripts/install_native.sh --domain gateway.example.com --email admin@example.com --with-monitoring
```

## Installation Options

| Option | Description |
|--------|-------------|
| `--domain DOMAIN` | Your domain name (e.g., gateway.example.com) |
| `--email EMAIL` | Email for SSL certificate notifications |
| `--skip-ssl` | Skip SSL setup (HTTP only, even with domain) |
| `--with-monitoring` | Install Prometheus & Grafana monitoring |
| `--skip-build` | Use existing binary (for reinstalls) |
| `--help` | Show all options |

## Domain Setup Instructions

### 1. Configure DNS
Before running the install script with `--domain`, set up your DNS:

**For subdomain (recommended):**
- Type: `A`
- Name: `gateway` (or your preferred subdomain)
- Value: `YOUR_SERVER_IP`
- TTL: `300` (5 minutes)

**For root domain:**
- Type: `A`
- Name: `@`
- Value: `YOUR_SERVER_IP`
- TTL: `300`

### 2. Verify DNS Propagation
```bash
# Check if your domain points to the server
dig +short gateway.example.com
nslookup gateway.example.com

# Should return your server's IP address
```

### 3. Install with Domain
```bash
sudo ./scripts/install_native.sh --domain gateway.example.com --email your@email.com
```

The installer will:
- Configure nginx reverse proxy
- Obtain SSL certificate via Let's Encrypt
- Set up automatic certificate renewal
- Configure HTTPS redirects

## What Gets Installed

### System Packages
- `golang-go` - Go compiler
- `nginx` - Web server/reverse proxy
- `certbot` - SSL certificate management
- `sqlite3` - Database
- `ffmpeg` - Video transcoding
- `fail2ban` - Intrusion prevention
- `ufw` - Uncomplicated Firewall
- Various utilities (curl, jq, bc, htop, etc.)

**Note:** Redis is **not required** - the gateway uses an efficient in-memory LRU cache.

### Directory Structure
```
/opt/torrent-gateway/
├── bin/gateway              # Main binary
├── configs/                 # Configuration files
├── data/                    # Application data
│   ├── blobs/              # Small file storage
│   ├── chunks/             # Chunked file pieces
│   └── metadata.db         # SQLite database
├── logs/                    # Application logs
├── scripts/                 # Management scripts
└── backups/                # Automated backups
```

### Services Created
- `torrent-gateway` - Main application service
- `nginx` - Web server (configured as reverse proxy)
- `redis-server` - Caching service
- `prometheus` - Metrics collection (optional)
- `grafana-server` - Metrics dashboard (optional)

## Post-Installation

### 1. Verify Installation
```bash
# Check service status
sudo systemctl status torrent-gateway
sudo systemctl status nginx

# Run health checks
sudo /opt/torrent-gateway/scripts/health_check.sh

# Test web access
curl http://localhost/api/health
# or with domain:
curl https://gateway.example.com/api/health
```

### 2. Access Web Interface
- **With domain:** https://gateway.example.com
- **Without domain:** http://YOUR_SERVER_IP
- **Admin panel:** https://gateway.example.com/admin
- **API:** https://gateway.example.com/api/

### 3. Monitoring (if installed)
- **Prometheus:** http://localhost:9090
- **Grafana:** http://localhost:3000 (admin/admin)

## Configuration

### Main Config
Edit `/opt/torrent-gateway/configs/config.yaml` and restart:
```bash
sudo nano /opt/torrent-gateway/configs/config.yaml
sudo systemctl restart torrent-gateway
```

### Nginx Config
For custom nginx settings:
```bash
sudo nano /etc/nginx/sites-available/torrent-gateway
sudo nginx -t
sudo systemctl restart nginx
```

## Management Commands

### Service Management
```bash
# Start/stop/restart
sudo systemctl start torrent-gateway
sudo systemctl stop torrent-gateway
sudo systemctl restart torrent-gateway

# View logs
sudo journalctl -u torrent-gateway -f
sudo tail -f /var/log/nginx/error.log
```

### SSL Certificate Management
```bash
# Check certificate status
sudo certbot certificates

# Renew certificates manually
sudo certbot renew

# Test renewal process
sudo certbot renew --dry-run
```

### Backup & Restore
```bash
# Create backup
sudo /opt/torrent-gateway/scripts/backup.sh

# List backups
ls -la /opt/torrent-gateway/backups/

# Restore from backup
sudo /opt/torrent-gateway/scripts/restore.sh TIMESTAMP
```

## Troubleshooting

### Common Issues

**SSL Certificate Failed:**
```bash
# Check DNS propagation
dig +short gateway.example.com

# Check firewall
sudo ufw status
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Manually get certificate
sudo certbot --nginx -d gateway.example.com
```

**Service Won't Start:**
```bash
# Check logs
sudo journalctl -u torrent-gateway -n 50

# Check config syntax
/opt/torrent-gateway/bin/gateway -config /opt/torrent-gateway/configs/config.yaml -check

# Check permissions
sudo chown -R torrent-gateway:torrent-gateway /opt/torrent-gateway/data
```

**Web Interface Not Loading:**
```bash
# Check nginx
sudo nginx -t
sudo systemctl status nginx

# Check proxy connection
curl http://localhost:9877/api/health
```

### Log Locations
- Application logs: `journalctl -u torrent-gateway`
- Nginx logs: `/var/log/nginx/`
- SSL logs: `/var/log/letsencrypt/`
- System logs: `/var/log/syslog`

## Firewall Configuration

The installer configures UFW with these rules:
- Port 22 (SSH)
- Port 80 (HTTP)
- Port 443 (HTTPS)
- Monitoring ports (localhost only)

### Manual Firewall Setup
```bash
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```

## Security Features

- Dedicated service user (non-root)
- Systemd security hardening
- Rate limiting for uploads/downloads
- SSL/TLS encryption (when domain configured)
- Security headers via nginx
- Firewall configuration
- Log rotation and cleanup

## Performance Tuning

### For High Traffic
Edit `/opt/torrent-gateway/configs/config.yaml`:
```yaml
rate_limiting:
  download:
    requests_per_second: 100.0
    burst_size: 200

transcoding:
  concurrent_jobs: 4  # Adjust based on CPU cores
```

### For Large Files
Edit `/etc/nginx/sites-available/torrent-gateway`:
```nginx
client_max_body_size 50G;  # Increase as needed
proxy_read_timeout 600s;   # For large uploads
```

## Monitoring & Maintenance

### Automated Tasks
The installer sets up cron jobs for:
- Daily backups (2 AM)
- Database maintenance (3 AM)
- Health checks (every 5 minutes)
- Log cleanup (weekly)

### Manual Maintenance
```bash
# Check disk usage
df -h /opt/torrent-gateway/

# Clean old files
sudo /opt/torrent-gateway/scripts/cleanup.sh

# Update application
cd /path/to/source
git pull
sudo ./scripts/install_native.sh --skip-build=false
```

## Uninstalling

```bash
# Stop services
sudo systemctl stop torrent-gateway nginx
sudo systemctl disable torrent-gateway

# Remove files (WARNING: This deletes all data!)
sudo rm -rf /opt/torrent-gateway
sudo rm /etc/systemd/system/torrent-gateway.service
sudo rm /etc/nginx/sites-available/torrent-gateway
sudo rm /etc/nginx/sites-enabled/torrent-gateway

# Remove user
sudo userdel torrent-gateway

# Remove packages (optional)
sudo apt remove golang-go nginx certbot python3-certbot-nginx

# Clean systemd
sudo systemctl daemon-reload
```

## Support

For issues, check:
1. This installation guide
2. `/docs/troubleshooting.md`
3. System logs and service status
4. GitHub issues for known problems

Installation complete! Your Torrent Gateway should now be running and accessible.