#!/usr/bin/env bash
# Installation script for Oracle Publisher Service in LXC container

set -euo pipefail

source /dev/stdin <<<"$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func 2>/dev/null || echo '')"

ORACLE_USER="${ORACLE_USER:-oracle}"
ORACLE_GROUP="${ORACLE_GROUP:-oracle}"
ORACLE_HOME="/opt/oracle-publisher"
ORACLE_DATA="/var/lib/oracle-publisher"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "Updating system packages..."
export LC_ALL=C
export LANG=C
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get upgrade -y -qq
apt-get install -y -qq \
    python3 \
    python3-pip \
    python3-venv \
    curl \
    wget \
    jq \
    git \
    ca-certificates

log_success "System packages updated"

log_info "Creating oracle user..."
if ! id -u "$ORACLE_USER" &>/dev/null; then
    useradd -r -s /bin/bash -d "$ORACLE_HOME" -m "$ORACLE_USER"
    log_success "Created oracle user"
else
    log_info "Oracle user already exists"
fi

# Create directories
log_info "Creating directories..."
mkdir -p "$ORACLE_HOME" "$ORACLE_DATA"
chown -R "$ORACLE_USER:$ORACLE_GROUP" "$ORACLE_HOME" "$ORACLE_DATA"

# Create Python virtual environment
log_info "Setting up Python environment..."
cd "$ORACLE_HOME"
su - "$ORACLE_USER" -c "python3 -m venv venv"

# Install dependencies
log_info "Installing Python dependencies..."
su - "$ORACLE_USER" -c "cd $ORACLE_HOME && source venv/bin/activate && \
    pip install --upgrade pip && \
    pip install web3 eth-account requests python-dotenv pydantic aiohttp \
    schedule prometheus-client opentelemetry-api opentelemetry-sdk \
    opentelemetry-exporter-otlp-proto-grpc opentelemetry-instrumentation-requests \
    opentelemetry-instrumentation-web3"

log_success "Python dependencies installed"

# Create configuration template
log_info "Creating configuration..."
cat > "$ORACLE_HOME/.env.template" <<'EOF'
# Oracle Publisher Configuration
RPC_URL_138=http://192.168.11.250:8545
ORACLE_CONTRACT_ADDRESS=
PRIVATE_KEY=
UPDATE_INTERVAL=30
HEARTBEAT_INTERVAL=300
DEVIATION_THRESHOLD=0.01

# Data Sources
DATA_SOURCE_1_URL=
DATA_SOURCE_1_PARSER=
DATA_SOURCE_2_URL=
DATA_SOURCE_2_PARSER=

# Metrics
METRICS_PORT=8000
METRICS_ENABLED=true

# OpenTelemetry (optional)
OTEL_ENABLED=false
OTEL_ENDPOINT=http://localhost:4317
EOF

chown "$ORACLE_USER:$ORACLE_GROUP" "$ORACLE_HOME/.env.template"

# Create systemd service
log_info "Creating systemd service..."
cat > /etc/systemd/system/oracle-publisher.service <<EOF
[Unit]
Description=Oracle Publisher Service
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=$ORACLE_USER
Group=$ORACLE_GROUP
WorkingDirectory=$ORACLE_HOME
Environment="PATH=$ORACLE_HOME/venv/bin:/usr/local/bin:/usr/bin:/bin"

# Load environment
EnvironmentFile=-$ORACLE_HOME/.env

# ExecStart
ExecStart=$ORACLE_HOME/venv/bin/python $ORACLE_HOME/oracle_publisher.py

# Restart
Restart=always
RestartSec=10

# Security
NoNewPrivileges=true
PrivateTmp=true

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=oracle-publisher

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload

log_success "Oracle Publisher installation completed!"
log_info "Next steps:"
log_info "1. Copy oracle_publisher.py to $ORACLE_HOME/"
log_info "2. Configure $ORACLE_HOME/.env"
log_info "3. Start service: systemctl start oracle-publisher"

