# DBManager - SCAR Chat Database Management Tool

Command-line utility for managing SCAR Chat user database.

## Overview

`dbmanager` provides a convenient interface for user administration without requiring direct SQL commands. It handles password hashing with Argon2, avatar management, and user queries.

## Database Location

DBManager searches for `scarchat.db` in the following order:
1. Current working directory
2. CMake install path: `/usr/local/share/scarchat/scarchat.db`
3. User home directory: `~/.local/share/scarchat/scarchat.db`

You can override this with the `--db` option.

## Usage

```bash
dbmanager [OPTIONS] COMMAND [ARGS...]
```

### Options

- `--db <path>` - Specify custom database path
- `--help` - Display help message

## Commands

### User Management

#### Add User
```bash
dbmanager adduser <username> <password> [avatar]
```
Creates a new user with automatic salt generation and Argon2 password hashing.

**Examples:**
```bash
dbmanager adduser alice password123
dbmanager adduser bob secret456 /path/to/avatar.png
```

#### Delete User
```bash
dbmanager deleteuser <username>
```
Removes a user from the database.

**Example:**
```bash
dbmanager deleteuser alice
```

### Modify User Fields

#### Change Password
```bash
dbmanager modifypass <username> <newpassword>
```
Updates user's password with new salt and hash.

**Example:**
```bash
dbmanager modifypass alice newpassword123
```

#### Update Avatar
```bash
dbmanager modifyavatar <username> <avatar_file>
```
Sets user's avatar image from file (PNG, JPG, etc.).

**Example:**
```bash
dbmanager modifyavatar alice /home/alice/profile.jpg
```

#### Update Email
```bash
dbmanager modifyemail <username> <email>
```
Sets user's email address.

**Example:**
```bash
dbmanager modifyemail alice alice@example.com
```

#### Update Role
```bash
dbmanager modifyrole <username> <role>
```
Sets user's role (e.g., admin, moderator, user).

**Example:**
```bash
dbmanager modifyrole alice admin
```

### Query Operations

#### Fetch User Details
```bash
dbmanager fetch <username>
```
Displays comprehensive information for a specific user.

**Example:**
```bash
dbmanager fetch alice
```

**Output:**
```
User ID: 1
Username: alice
Status: Offline
Email: alice@example.com
Role: admin
Last Login: Sun Dec  7 10:30:45 2025
Has Avatar: Yes
Token: eyJhbGciOiJIUzI1Ni...
Salt: a1b2c3d4e5f6...
Password Hash: $argon2id$v=19$m=...
```

#### Search Users
```bash
dbmanager search <field> <value>
```
Searches users by username, email, or role.

**Fields:** `username`, `email`, `role`

**Example:**
```bash
dbmanager search role admin
dbmanager search username alice
dbmanager search email @example.com
```

#### List All Users
```bash
dbmanager list
```
Displays a table of all users with status information.

**Example Output:**
```
Total users: 3
Username             Status     Email                     Role            Last Login          
alice                Offline    alice@example.com         admin           2025-12-07 10:30:45
bob                  Online     bob@example.com           user            2025-12-07 11:15:20
charlie              Offline    (not set)                 moderator       Never
```

## Advanced Usage

### Custom Database Location
```bash
dbmanager --db /custom/path/chat.db list
dbmanager --db ~/databases/scarchat.db adduser test password
```

### Batch Operations
```bash
# Create multiple users
for user in alice bob charlie; do
    dbmanager adduser "$user" "password123"
done

# Update all users to default role
dbmanager list | tail -n +4 | awk '{print $1}' | while read user; do
    dbmanager modifyrole "$user" "user"
done
```

### Integration with Scripts
```bash
#!/bin/bash
# Setup test environment

# Create admin user
dbmanager adduser admin admin123
dbmanager modifyrole admin admin
dbmanager modifyemail admin admin@localhost

# Create test users
for i in {1..10}; do
    dbmanager adduser "user$i" "pass$i"
done

echo "Test environment ready!"
```

## Password Security

- **Algorithm:** Argon2id (PHC winner)
- **Time Cost:** 2 iterations
- **Memory Cost:** 64 MB
- **Parallelism:** 4 threads
- **Salt:** 16-byte random per user
- **Hash Length:** 32 bytes

## Database Schema

The `users` table has the following structure:

| Column      | Type    | Description                      |
|-------------|---------|----------------------------------|
| id          | INTEGER | Primary key (auto-increment)     |
| username    | TEXT    | Unique username                  |
| password    | TEXT    | Argon2 hash                      |
| salt        | TEXT    | Random salt (hex)                |
| token       | TEXT    | JWT session token                |
| status      | TEXT    | 'online' or 'offline'            |
| role        | TEXT    | User role (admin, user, etc.)    |
| email       | TEXT    | Email address                    |
| last_login  | INTEGER | Unix timestamp                   |
| avatar_pic  | BLOB    | Avatar image data                |

## Build

DBManager is built automatically with the SCAR Chat project:

```bash
cmake -B build
cmake --build build
./build/dbmanager/dbmanager --help
```

## Installation

```bash
sudo cmake --install build
dbmanager --help
```

Default install locations:
- Binary: `/usr/local/bin/dbmanager`
- Database: `/usr/local/share/scarchat/scarchat.db`

## Troubleshooting

### Database Not Found
```
Error: Failed to initialize database: scarchat.db
```
**Solution:** Use `--db` to specify path or create database first:
```bash
touch scarchat.db
dbmanager adduser testuser testpass
```

### User Already Exists
```
Error: User 'alice' already exists
```
**Solution:** Delete existing user first or choose different username:
```bash
dbmanager deleteuser alice
dbmanager adduser alice newpassword
```

### Avatar File Not Found
```
Error: Failed to read avatar file
```
**Solution:** Verify file path and permissions:
```bash
ls -l /path/to/avatar.png
dbmanager modifyavatar alice "$(realpath avatar.png)"
```

## See Also

- `PROGRESS-DBMANAGER.md` - Implementation status
- `server/database/database.h` - Database API
- `shared/crypto/argon2_wrapper.h` - Password hashing

## License

Same as SCAR Chat project.
