Metadata-Version: 2.4
Name: ocn-cli
Version: 1.2.0
Summary: Diagnostic CLI tool for OCN (Open Control Network) servers
Author: OCN Development Team
License: MIT
Project-URL: Repository, https://github.com/your-org/ocn
Project-URL: Documentation, https://github.com/your-org/ocn/tree/main/cli
Project-URL: Issues, https://github.com/your-org/ocn/issues
Keywords: ocn,diagnostics,cli,ssh,building-automation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Topic :: System :: Systems Administration
Classifier: Topic :: Utilities
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typer>=0.12.0
Requires-Dist: paramiko>=3.4.0
Requires-Dist: prompt-toolkit>=3.0.43
Requires-Dist: rich>=13.7.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: mypy>=1.8.0; extra == "dev"
Requires-Dist: ruff>=0.3.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Dynamic: license-file

# OCN CLI - Diagnostic Tool for OCN Servers

[![PyPI version](https://badge.fury.io/py/ocn-cli.svg)](https://badge.fury.io/py/ocn-cli)
[![Python](https://img.shields.io/pypi/pyversions/ocn-cli.svg)](https://pypi.org/project/ocn-cli/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A cross-platform, Python-based command-line interface for remote troubleshooting and diagnostics of OCN (Open Control Network) server installations.

## Features

- 🔐 **Secure Authentication** - SSH key-based authentication
- 🔌 **Interactive Shell** - Persistent SSH session with command history and autocomplete
- 💡 **Syntax Highlighting** - Color-coded commands for better readability
- 🎯 **Helper Commands** - Built-in diagnostic commands for common operations
- 🌐 **Cross-Platform** - Works on Windows, macOS, and Linux
- 🛡️ **Security** - Permission validation and secure key handling

## Installation

### Prerequisites

- Python 3.9 or higher
- pip package manager

### Install from PyPI

```bash
pip install ocn-cli
```

### Install from Source (Development)

```bash
git clone https://github.com/your-org/ocn.git
cd ocn/cli
pip install -e .
```

## Usage

### Basic Connection

Connect to an OCN server with your SSH key:

```bash
ocn-cli --host server.ocn.local --key ~/.ssh/id_rsa
```

When you connect, you'll be prompted for a sudo password (optional, needed for Docker diagnostics):

```
🔑 Enter sudo password for remote server (optional, press Enter to skip):
Validating sudo credentials...
✅ Sudo credentials validated
```

If the password is incorrect, you'll see a warning but can continue (some diagnostics may fail).

### Provide Sudo Password

Some diagnostics require sudo (Docker commands, system checks). You can provide the password via:

```bash
# Recommended: Will prompt for password (masked input)
ocn-cli --host server.ocn.local --key ~/.ssh/id_rsa

# Or provide it upfront (less secure - visible in command history)
ocn-cli --host server.ocn.local --key ~/.ssh/id_rsa --sudo-password yourpassword
```

**Note:** The sudo password is validated upon connection. If invalid, you'll see a warning and can continue without sudo (some diagnostics will be skipped).

### Custom User and Port

Specify a different SSH user and port:

```bash
ocn-cli --host 192.168.1.100 --key ~/.ssh/ocn_key --user admin --port 2222
```

### Full Options

```bash
ocn-cli --help
```

## Helper Commands

Once connected, the interactive shell provides several built-in helper commands:

| Command | Description |
|---------|-------------|
| `help` | Show available helper commands |
| `status` | Display system status (uptime, CPU, memory, disk) |
| `diagnose` | Run comprehensive server diagnostics (checks network, Docker, resources, services) |
| `offline-update` | Upload and apply offline OCN update package (for servers without internet) |
| `onboard` | Onboard OCN server to OCN-cloud (remove OpenVPN, set hostname, join Tailscale, reboot) |
| `clear` | Clear the terminal screen |
| `exit` or `quit` | Exit the interactive shell |

Any other command is executed directly on the remote OCN server.

## Examples

### Check Server Status

```
ocn@server.ocn.local>> status

╭─── System Status ────────────────────────╮
│                                          │
│ Uptime:    5 days, 12:34:56             │
│ CPU Load:  2.5, 2.3, 2.1 (1/5/15 min)   │
│ Memory:    4.2G / 8.0G (52%)            │
│ Disk:      45G / 100G (45%)             │
│                                          │
╰──────────────────────────────────────────╯
```

### Run Comprehensive Diagnostics

```
ocn@server.ocn.local>> diagnose

╭─── OCN Server Diagnostic Report ───────────────────────╮
│ Server: ocn-server-01                                  │
│ Health Score: 85% (14/17 checks passed)                │
╰─────────────────────────────────────────────────────────╯

━━━ Network Diagnostics ━━━
✅ internet_connectivity       OK (3/3 endpoints reachable)
✅ dns_resolution               OK (all 4 domains resolved)
✅ keygen_accessibility         OK (HTTP 200)

━━━ Docker Diagnostics ━━━
❌ docker_installation          FAIL - docker.io detected
   Remediation:
   • Remove docker.io: sudo apt remove docker.io
   • Install official Docker from get.docker.com
   
✅ container_status             OK (5/5 containers running)

━━━ Resources ━━━
✅ cpu_usage                    OK (15.2%)
✅ memory_usage                 OK (RAM: 45%, Swap: 2%)
⚠️  disk_space                  HIGH (/ at 87%)
✅ system_load                  OK (1.2, 1.5, 1.3)

━━━ Services ━━━
✅ docker_daemon                Active
✅ nginx_service                Active
✅ firewall                     Active (ufw)
```

### Execute Remote Commands

```
ocn@server.ocn.local>> docker ps
CONTAINER ID   IMAGE          COMMAND       STATUS
abc123def456   ocn-backend    "dotnet..."   Up 5 days

ocn@server.ocn.local>> journalctl -u ocn-api -n 20
-- Logs begin at Mon 2024-01-01 00:00:00 UTC --
...
```

### Diagnose Command Options

```
# Run all diagnostics
diagnose

# Quick mode (critical checks only)
diagnose --quick

# Check specific category
diagnose --category docker

# Save report to file
diagnose --output report.html --format html

# Get help
diagnose --help
```

### Offline Update (For Servers Without Internet)

```
# Upload and apply an offline update package
offline-update --package /local/path/to/ocn-update-2.1.10.tar.gz

# Process:
#  1. Uploads package via SFTP (with progress bar)
#  2. Validates package structure
#  3. Shows update preview
#  4. Prompts for confirmation
#  5. Applies update (stops containers, loads images, restarts)

# See OFFLINE_UPDATES.md for complete guide
```

### Onboard to OCN-Cloud

```
# Onboard server to OCN-cloud (Debian/Ubuntu only)
onboard --auth-key tskey-auth-xxx --hostname ocn-server-01

# Process:
#  1. Removes OpenVPN/openvpn3/connexa and disables openvpn* services
#  2. Sets hostname via hostnamectl
#  3. Installs Tailscale (if needed) and joins with auth key
#  4. Reboots the server (session will disconnect)

# Requires: sudo password when connecting, Debian/Ubuntu
```

**See:** [OCN_CLOUD_ONBOARD.md](OCN_CLOUD_ONBOARD.md) for a complete step-by-step guide from installing Python to running the onboard command.

### Use Tab Completion

Type a partial command and press `Tab` to see suggestions:

```
ocn@server.ocn.local>> doc<TAB>
docker
```

### Command History

Use arrow keys to navigate through previous commands:

- `↑` - Previous command
- `↓` - Next command
- `Ctrl+R` - Reverse search through history

## SSH Key Setup

### Generating an SSH Key

If you don't have an SSH key, generate one:

```bash
# RSA key (widely supported)
ssh-keygen -t rsa -b 4096 -f ~/.ssh/ocn_key

# Ed25519 key (modern, more secure)
ssh-keygen -t ed25519 -f ~/.ssh/ocn_key

# Set secure permissions
chmod 600 ~/.ssh/ocn_key
```

### Authorizing Your Key on OCN Server

Add your public key to the OCN server:

```bash
# Method 1: Using ssh-copy-id
ssh-copy-id -i ~/.ssh/ocn_key.pub user@server.ocn.local

# Method 2: Manual
cat ~/.ssh/ocn_key.pub | ssh user@server.ocn.local "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
```

### Key Requirements

- Must be a valid SSH private key (RSA, Ed25519, ECDSA, or DSA)
- File permissions should be `600` (read/write for owner only)
- Key must be authorized on the OCN server (`~/.ssh/authorized_keys`)
- Passphrase-protected keys are not currently supported

## Troubleshooting

### Connection Failed

**Error:** `Connection refused`

- Verify SSH service is running on the OCN server: `systemctl status sshd`
- Check firewall rules allow SSH connections on the specified port
- Confirm the server is reachable: `ping server.ocn.local`

**Error:** `Authentication failed`

- Ensure your SSH key is authorized on the server
- Check `~/.ssh/authorized_keys` on the OCN server contains your public key
- Verify file permissions: `chmod 600 ~/.ssh/your_key`
- Try using a different key with `--key` option

**Error:** `Network unreachable`

- Check network connectivity
- Verify DNS resolution: `nslookup server.ocn.local`
- Confirm VPN connection if required

### Key Permission Warnings

**Warning:** `Key file has insecure permissions`

Fix with:
```bash
chmod 600 ~/.ssh/your_key
```

## Development

### Setup Development Environment

```bash
# Clone repository
git clone https://github.com/your-org/ocn.git
cd ocn/cli

# Create virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install with development dependencies
pip install -e ".[dev]"
```

### Run Tests

```bash
pytest
```

### Code Quality

```bash
# Type checking
mypy ocn_cli

# Linting
ruff check ocn_cli

# Formatting
black ocn_cli
```


## Architecture

The OCN CLI follows a modular architecture:

- **CLI Layer** (`cli.py`) - Typer-based command-line interface
- **Authentication Layer** (`auth/`) - SSH key management
- **SSH Layer** (`ssh/`) - Connection management, command execution
- **Shell Layer** (`shell/`) - Interactive REPL, history, autocomplete, syntax highlighting
- **Commands Layer** (`commands/`) - Helper command registry and implementations
- **UI Layer** (`ui/`) - Rich-based output formatting and messages
- **Utils Layer** (`utils/`) - Platform utilities and security helpers

## Contributing

Please read `AGENTS.md` for guidelines on contributing to this project.

## Publishing

To publish a new version of OCN CLI to PyPI, see [`PUBLISHING.md`](PUBLISHING.md) for detailed instructions on:
- Setting up PyPI trusted publishing
- Creating releases via GitHub
- Automated publishing with GitHub Actions
- Manual publishing workflow

Quick publish:
```bash
# 1. Update version in ocn_cli/version.py
# 2. Update CHANGELOG.md
# 3. Create GitHub release with tag cli-vX.Y.Z
# 4. GitHub Actions automatically publishes to PyPI
```

## License

MIT License - See LICENSE file for details.

## Support

For issues, questions, or feature requests:
- GitHub Issues: https://github.com/your-org/ocn/issues
- Documentation: https://github.com/your-org/ocn/tree/main/cli

## Version

Current version: 1.0.0

See `CHANGELOG.md` for version history and changes.

