# Mosaic Stack Setup Scripts

Comprehensive setup wizard for Mosaic Stack, inspired by the [Calibr setup pattern](https://github.com/noahwoltje/calibr).

## Quick Start

```bash
# Interactive setup (recommended)
./scripts/setup.sh

# Non-interactive Docker with SSO
./scripts/setup.sh --non-interactive --mode docker --enable-sso --bundled-authentik

# Dry run to see what would happen
./scripts/setup.sh --dry-run --mode docker
```

## Current Status

**✅ Implemented (Foundation):**

- Platform detection (Ubuntu, Arch, macOS)
- Dependency checking (Docker, Node.js, pnpm, PostgreSQL)
- Dependency installation
- Mode selection (Docker vs Native)
- Argument parsing
- Comprehensive logging
- Common utility functions library

**🚧 To Be Implemented:**

- Complete configuration collection (SSO, Ollama, MoltBot, URLs)
- .env file generation with smart preservation
- Port conflict detection
- Password/secret generation
- Authentik blueprint auto-configuration
- Docker deployment execution
- Post-install instructions

See full implementation plan in [issue tracking](https://git.mosaicstack.dev/mosaic/stack/issues).

## Files

```
scripts/
├── setup.sh              # Main setup wizard (foundation complete)
├── lib/
│   ├── common.sh         # Utility functions (complete)
│   └── docker.sh         # Docker-specific functions (TODO)
└── templates/
    └── .env.template     # Template for .env generation (TODO)
```

## Features

### Platform Detection

Automatically detects:

- Operating system (Ubuntu, Arch, Fedora, macOS)
- Package manager (apt, pacman, dnf, brew)
- Installed dependencies

### Dependency Management

Checks and optionally installs:

- **Docker mode:** Docker, Docker Compose
- **Native mode:** Node.js 18+, pnpm, PostgreSQL

### Interactive Mode

User-friendly wizard with:

- Color-coded output
- Clear prompts and defaults
- Yes/no confirmations
- Numbered menu selections

### Non-Interactive Mode

Suitable for CI/CD:

```bash
./scripts/setup.sh \
  --non-interactive \
  --mode docker \
  --enable-sso \
  --bundled-authentik \
  --ollama-mode local
```

### Dry Run

Preview changes without execution:

```bash
./scripts/setup.sh --dry-run --mode docker
```

## Common Functions (lib/common.sh)

### Output Functions

- `print_header()` - Section headers
- `print_success()` - Success messages (green ✓)
- `print_error()` - Error messages (red ✗)
- `print_warning()` - Warnings (yellow ⚠)
- `print_info()` - Info messages (blue ℹ)
- `print_step()` - Step indicators (cyan →)

### User Input

- `confirm()` - Yes/no prompts with defaults
- `select_option()` - Numbered menu selection

### Platform Detection

- `detect_os()` - Detect operating system
- `detect_package_manager()` - Detect package manager
- `get_os_name()` - Human-readable OS name

### Dependency Checking

- `check_command()` - Check if command exists
- `check_docker()` - Check Docker installation and daemon
- `check_docker_compose()` - Check Docker Compose
- `check_node()` - Check Node.js version
- `check_pnpm()` - Check pnpm installation
- `check_postgres()` - Check PostgreSQL

### Package Installation

- `get_package_name()` - Get package name for specific manager
- `install_package()` - Install package via detected manager
- `check_sudo()` - Check/request sudo access

### Validation

- `validate_url()` - Validate URL format
- `validate_email()` - Validate email format
- `validate_port()` - Validate port number (1-65535)
- `validate_domain()` - Validate domain name

### Secret Generation

- `generate_secret()` - Cryptographically secure random (with special chars)
- `generate_password()` - User-friendly password (alphanumeric only)
- `mask_value()` - Mask sensitive values for display
- `is_placeholder()` - Detect placeholder values

### .env Management

- `parse_env_file()` - Parse .env into associative array
- `get_env_value()` - Get value from parsed env
- `set_env_value()` - Set value in env array

### File Operations

- `backup_file()` - Create timestamped backup

### Port Checking

- `check_port_in_use()` - Check if port is in use
- `suggest_alternative_port()` - Suggest alternative if conflict

## Logging

All output is logged to `logs/setup-YYYYMMDD_HHMMSS.log`:

- Clean output to console
- Full trace (set -x) to log file only
- Errors and warnings to both

## CLI Options

```
--non-interactive       Run without prompts (requires all options)
--dry-run              Show what would happen without executing
--mode MODE            Deployment mode: docker or native
--enable-sso           Enable Authentik SSO (Docker mode only)
--bundled-authentik    Use bundled Authentik server (with --enable-sso)
--external-authentik URL  Use external Authentik server URL
--ollama-mode MODE     Ollama mode: local, remote, disabled (default)
--ollama-url URL       Ollama server URL (if remote)
--enable-moltbot       Enable MoltBot integration
--base-url URL         Mosaic base URL (e.g., https://mosaic.example.com)
--help                 Show help
```

## Next Steps for Implementation

### 1. Configuration Collection (High Priority)

- [ ] URL and domain configuration
- [ ] SSO setup (bundled vs external Authentik)
- [ ] Ollama configuration (local/remote/disabled)
- [ ] MoltBot toggle
- [ ] Existing config detection and smart updates

### 2. .env Generation (High Priority)

- [ ] Create .env template
- [ ] Generate passwords/secrets securely
- [ ] Preserve existing non-placeholder values
- [ ] Apply port overrides
- [ ] Write .admin-credentials file

### 3. Port Conflict Detection

- [ ] Check: 3000, 3001 (web), 4000 (API), 5432 (PostgreSQL), 6379 (Valkey), 9000/9443 (Authentik)
- [ ] Suggest alternatives automatically
- [ ] Update .env with overrides

### 4. Authentik Blueprint Auto-Configuration

- [ ] Copy blueprint to authentik-blueprints/
- [ ] Create docker-compose.authentik.yml overlay
- [ ] Mount blueprint volume
- [ ] Document post-install steps (initial setup, client secret)

### 5. Deployment Execution

- [ ] Docker: docker compose up -d
- [ ] Native: pnpm install, database setup, migrations
- [ ] Health checks

### 6. Post-Install Instructions

- [ ] Show URLs (web, API, Authentik)
- [ ] Show credentials location
- [ ] Next steps checklist
- [ ] Troubleshooting tips

### 7. Testing

- [ ] Test on Ubuntu, Arch, macOS
- [ ] Test interactive mode
- [ ] Test non-interactive mode
- [ ] Test dry-run mode
- [ ] Test existing .env preservation
- [ ] Test port conflict handling

## Contributing

When extending this setup script:

1. Follow the Calibr pattern for consistency
2. Add utility functions to `lib/common.sh`
3. Keep main `setup.sh` focused on orchestration
4. Test both interactive and non-interactive modes
5. Update this README with new features

## Reference

Original pattern: `~/src/calibr/scripts/setup.sh` (1,327 lines)

Key patterns to follow:

- Comprehensive error handling
- Clear user communication
- Smart existing config detection
- Secure secret generation
- Dry-run capability
- Both interactive and non-interactive modes
