# Corrosion Companion Agent

The Companion Agent is a lightweight Go binary that runs on bare metal Rust dedicated servers to provide process management, file operations, and SteamCMD integration for servers not running on managed game server panels (AMP/Pterodactyl).

## Features

- **NATS Integration**: Connects to Corrosion cloud via NATS with token authentication
- **Process Management**: Start, stop, restart, and monitor game server process
- **File Operations**: Remote file management (read, write, delete, list)
- **SteamCMD Integration**: Automatic server updates via SteamCMD
- **Self-Update**: Download and apply agent updates from the cloud
- **Heartbeat Monitoring**: Publishes status every 60 seconds
- **Graceful Shutdown**: Handles SIGTERM/SIGINT for clean shutdowns
- **Crash Detection**: Monitors server process and reports crashes
- **Zero Configuration**: Pre-configured binary downloaded from dashboard

## Architecture

```
┌─────────────────────────────────────────────┐
│         Corrosion Cloud (NATS)              │
│   corrosion.{license_id}.cmd.*              │
│   corrosion.{license_id}.files.*            │
│   corrosion.{license_id}.update.steam       │
└──────────────────┬──────────────────────────┘
                   │ (Outbound connection)
                   │
         ┌─────────▼──────────┐
         │  Companion Agent   │
         │  (This binary)     │
         └─────────┬──────────┘
                   │
         ┌─────────▼──────────┐
         │   Rust Dedicated   │
         │   Server Process   │
         └────────────────────┘
```

## Installation

### Prerequisites

- Linux server (Ubuntu/Debian recommended) or Windows Server
- SteamCMD installed
- Rust Dedicated Server installed

### Quick Start

1. **Download** the pre-configured binary from your Corrosion dashboard
2. **Make executable** (Linux only):
   ```bash
   chmod +x corrosion-companion-linux-amd64
   ```

3. **Set environment variables**:
   ```bash
   export NATS_URL="nats://nats.corrosionmgmt.com:4222"
   export NATS_TOKEN="your-companion-token-from-dashboard"
   export LICENSE_ID="your-license-uuid"
   export GAME_SERVER_PATH="/home/rustserver/RustDedicated"
   export STEAMCMD_PATH="/usr/games/steamcmd"
   ```

4. **Run** the agent:
   ```bash
   ./corrosion-companion-linux-amd64
   ```

### Production Deployment (Linux with systemd)

1. **Copy binary** to system location:
   ```bash
   sudo cp corrosion-companion-linux-amd64 /usr/local/bin/corrosion-companion
   ```

2. **Create environment file**:
   ```bash
   sudo mkdir -p /etc/corrosion-companion
   sudo nano /etc/corrosion-companion/config.env
   ```

   Add:
   ```env
   NATS_URL=nats://nats.corrosionmgmt.com:4222
   NATS_TOKEN=your-companion-token-from-dashboard
   LICENSE_ID=your-license-uuid
   GAME_SERVER_PATH=/home/rustserver/RustDedicated
   STEAMCMD_PATH=/usr/games/steamcmd
   GAME_SERVER_ARGS=-batchmode +server.port 28015 +server.identity "myserver"
   HEARTBEAT_INTERVAL=60
   ```

3. **Create systemd service**:
   ```bash
   sudo nano /etc/systemd/system/corrosion-companion.service
   ```

   Add:
   ```ini
   [Unit]
   Description=Corrosion Companion Agent
   After=network.target

   [Service]
   Type=simple
   User=rustserver
   Group=rustserver
   EnvironmentFile=/etc/corrosion-companion/config.env
   ExecStart=/usr/local/bin/corrosion-companion
   Restart=always
   RestartSec=10
   StandardOutput=journal
   StandardError=journal

   [Install]
   WantedBy=multi-user.target
   ```

4. **Enable and start**:
   ```bash
   sudo systemctl daemon-reload
   sudo systemctl enable corrosion-companion
   sudo systemctl start corrosion-companion
   ```

5. **Check status**:
   ```bash
   sudo systemctl status corrosion-companion
   sudo journalctl -u corrosion-companion -f
   ```

## Configuration

All configuration is done via environment variables:

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `NATS_URL` | Yes | - | NATS server URL |
| `NATS_TOKEN` | Yes | - | Authentication token from dashboard |
| `LICENSE_ID` | Yes | - | Your Corrosion license UUID |
| `GAME_SERVER_PATH` | Yes | - | Full path to game server executable |
| `STEAMCMD_PATH` | No | `/usr/games/steamcmd` | Full path to steamcmd |
| `GAME_SERVER_ARGS` | No | `-batchmode` | Arguments to pass to game server |
| `HEARTBEAT_INTERVAL` | No | `60` | Heartbeat interval in seconds |
| `LOG_LEVEL` | No | `info` | Log verbosity (info/debug/warn/error) |

## NATS Subject Reference

### Published by Companion

| Subject | Payload | Frequency |
|---------|---------|-----------|
| `corrosion.{license_id}.companion.heartbeat` | Status, uptime, disk, CPU | Every 60s |
| `corrosion.{license_id}.files.response` | File operation results | On request |

### Subscribed by Companion

| Subject | Purpose |
|---------|---------|
| `corrosion.{license_id}.cmd.server` | Start/stop/restart commands |
| `corrosion.{license_id}.files.get` | Read file |
| `corrosion.{license_id}.files.put` | Write file |
| `corrosion.{license_id}.files.delete` | Delete file |
| `corrosion.{license_id}.files.list` | List directory |
| `corrosion.{license_id}.update.steam` | Trigger SteamCMD update |
| `corrosion.{license_id}.update.companion` | Self-update command |

## Building from Source

### Prerequisites

- Go 1.21 or later
- Make (optional, but recommended)

### Build Commands

```bash
# Download dependencies
go mod download

# Build for current platform
make build-local

# Build for Linux (amd64)
make build-linux

# Build for Windows (amd64)
make build-windows

# Build for all platforms
make build

# Run tests
make test

# Format code
make fmt
```

Binaries are output to `bin/` directory.

## Troubleshooting

### Agent won't connect to NATS

- Verify `NATS_URL` is correct
- Check firewall allows outbound connections to port 4222
- Verify `NATS_TOKEN` is valid from dashboard
- Check logs: `journalctl -u corrosion-companion -n 50`

### Server won't start

- Verify `GAME_SERVER_PATH` points to the correct executable
- Check file permissions (agent needs execute permission on server binary)
- Verify `GAME_SERVER_ARGS` are correct for your server
- Check server logs for startup errors

### SteamCMD updates fail

- Verify `STEAMCMD_PATH` is correct
- Check SteamCMD is installed: `steamcmd +quit`
- Ensure disk space is available
- Check network connectivity to Steam servers

### Self-update fails

- Verify agent has write permission to its own directory
- Check download URL is accessible
- Ensure sufficient disk space
- Restart agent manually after update if automatic restart fails

## Security Considerations

- **Token Security**: Keep `NATS_TOKEN` secret. It grants full control over your server.
- **File Operations**: The agent can read/write/delete files. It runs with the permissions of the user running it.
- **Process Control**: The agent can start/stop the game server process.
- **Network**: The agent only makes outbound connections (no inbound ports required).
- **Updates**: Self-updates download from URLs provided by Corrosion cloud (signed URLs).

## Support

- **Documentation**: https://docs.corrosionmgmt.com
- **Dashboard**: https://panel.corrosionmgmt.com
- **Issues**: Report via dashboard or contact support

## License

Proprietary software. Licensed to Corrosion platform users only.

## Version History

### 1.0.0 (2026-02-15)
- Initial release
- NATS connectivity with token auth
- Process management (start/stop/restart)
- File operations (read/write/delete/list)
- SteamCMD integration
- Self-update capability
- Heartbeat monitoring
- Graceful shutdown handling
