#!/usr/bin/env bash
set -euo pipefail

# Deploy Oxidized on tsys-librenms
# Part of OAM platform [#337]
# Network device config backup/versioning

echo "=== Setting up Oxidized ==="

mkdir -p /opt/oam/oxidized/{config,git-repos,logs}

# Config file
cat > /opt/oam/oxidized/config/config <<'CFGEOF'
---
username: 'CHANGE_ME'
password: 'CHANGE_ME'
model: powerconnect
interval: 3600
use_syslog: false
debug: false
threads: 30
timeout: 20
retries: 3
prompt: !ruby/regexp /([\w.@-]+[#>]\s?)n/
rest: 0.0.0.0:8888
next_adds_job: false
pid: /home/oxidized/.config/oxidized/pid
log: /home/oxidized/.config/oxidized/logs/log
snmp: false
resolve_dns: true
interval: 3600
output:
  default: git
  git:
    user: oxidized
    email: oxidized@tsys-librenms.knel.net
    repo: /home/oxidized/.config/oxidized/git-repos
source:
  default: csv
  csv:
    file: /home/oxidized/.config/oxidized/router.db
    delimiter: !ruby/regexp /:/
    map:
      name: 0
      model: 1
      username: 2
      password: 3
    gpg: false
CFGEOF

# Router DB (device list)
cat > /opt/oam/oxidized/config/router.db <<'DBEOF'
pfv-r5-core-01.knel.net:powerconnect:CHANGE_ME:CHANGE_ME
pfv-r3-tor-mgmt-01.knel.net:powerconnect:CHANGE_ME:CHANGE_ME
pfv-r3-tor-stor-01.knel.net:powerconnect:CHANGE_ME:CHANGE_ME
pfv-r6-mgmt-01.knel.net:powerconnect:CHANGE_ME:CHANGE_ME
DBEOF

# Docker compose
cat > /opt/oam/oxidized/docker-compose.yml <<'DCEOF'
services:
  oxidized:
    image: oxidized/oxidized:0.30.1
    container_name: oam-oxidized
    environment:
      - TZ=America/Chicago
    volumes:
      - /opt/oam/oxidized/config:/home/oxidized/.config/oxidized
    ports:
      - "8083:8888"
    restart: unless-stopped
DCEOF

echo "=== Pulling Oxidized image ==="
cd /opt/oam/oxidized && timeout 120 docker compose pull 2>&1

echo "=== Starting Oxidized ==="
cd /opt/oam/oxidized && docker compose up -d 2>&1

echo "=== Status ==="
docker ps --filter name=oam-oxidized --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

echo ""
echo "=== IMPORTANT ==="
echo "Oxidized deployed with placeholder credentials (CHANGE_ME)."
echo "Update /opt/oam/oxidized/config/router.db with real switch credentials"
echo "(username:password per device) to enable config backups."
echo "Then restart: cd /opt/oam/oxidized && docker compose restart"
echo ""
echo "=== Oxidized REST API: http://tsys-librenms.knel.net:8083 ==="
