#!/usr/bin/env bash
# Installation script for Hyperledger Firefly in LXC container
# Firefly is a Web3 gateway for enterprise blockchain applications

set -euo pipefail

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

FIREFLY_VERSION="${FIREFLY_VERSION:-v1.2.0}"
FIREFLY_USER="${FIREFLY_USER:-firefly}"
FIREFLY_GROUP="${FIREFLY_GROUP:-firefly}"
FIREFLY_HOME="/opt/firefly"
FIREFLY_DATA="/var/lib/firefly"

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 \
    docker.io \
    docker-compose \
    postgresql-client \
    curl \
    wget \
    jq \
    ca-certificates \
    gnupg \
    lsb-release

log_success "System packages updated"

# Start Docker
systemctl enable docker
systemctl start docker

log_info "Creating firefly user..."
if ! id -u "$FIREFLY_USER" &>/dev/null; then
    useradd -r -s /bin/bash -d "$FIREFLY_HOME" -m "$FIREFLY_USER"
    usermod -aG docker "$FIREFLY_USER"
    log_success "Created firefly user"
else
    log_info "Firefly user already exists"
    usermod -aG docker "$FIREFLY_USER"
fi

# Create directories
log_info "Creating directories..."
mkdir -p "$FIREFLY_HOME" "$FIREFLY_DATA"
chown -R "$FIREFLY_USER:$FIREFLY_GROUP" "$FIREFLY_HOME" "$FIREFLY_DATA"

# Download Firefly docker-compose
log_info "Downloading Firefly configuration..."
cd "$FIREFLY_HOME"

# Create docker-compose.yml
cat > docker-compose.yml <<'EOF'
version: '3.8'

services:
  postgres:
    image: postgres:15-alpine
    container_name: firefly-postgres
    environment:
      POSTGRES_USER: firefly
      POSTGRES_PASSWORD: ${DB_PASSWORD:-firefly}
      POSTGRES_DB: firefly
    volumes:
      - postgres-data:/var/lib/postgresql/data
    restart: unless-stopped
    networks:
      - firefly-network

  ipfs:
    image: ipfs/kubo:latest
    container_name: firefly-ipfs
    ports:
      - "5001:5001"
      - "4001:4001"
    volumes:
      - ipfs-data:/data/ipfs
    restart: unless-stopped
    networks:
      - firefly-network

  firefly-core:
    image: hyperledger/firefly:${FIREFLY_VERSION:-v1.2.0}
    container_name: firefly-core
    depends_on:
      - postgres
      - ipfs
    environment:
      - FF_DATABASE_TYPE=postgres
      - FF_DATABASE_URL=postgres://firefly:${DB_PASSWORD:-firefly}@postgres:5432/firefly?sslmode=disable
      - FF_BLOCKCHAIN_TYPE=ethereum
      - FF_BLOCKCHAIN_RPC=${BESU_RPC_URL:-http://192.168.11.250:8545}
      - FF_BLOCKCHAIN_WS=${BESU_WS_URL:-ws://192.168.11.250:8546}
      - FF_CHAIN_ID=${CHAIN_ID:-138}
      - FF_NODE_NAME=firefly-node-1
      - FF_API_PUBLICURL=${PUBLIC_URL:-http://localhost:5000}
      - FF_IPFS_API=http://ipfs:5001
      - FF_IPFS_GATEWAY=http://ipfs:8080
      - FF_LOGGING_LEVEL=info
    ports:
      - "5000:5000"
      - "5001:5001"
    volumes:
      - firefly-data:/var/lib/firefly
    restart: unless-stopped
    networks:
      - firefly-network

volumes:
  postgres-data:
  ipfs-data:
  firefly-data:

networks:
  firefly-network:
    driver: bridge
EOF

chown -R "$FIREFLY_USER:$FIREFLY_GROUP" "$FIREFLY_HOME"

log_success "Firefly configuration created"

# Create systemd service
log_info "Creating systemd service..."
cat > /etc/systemd/system/firefly.service <<EOF
[Unit]
Description=Hyperledger Firefly
After=docker.service postgresql.service
Requires=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=$FIREFLY_HOME
User=$FIREFLY_USER
Group=$FIREFLY_GROUP
ExecStart=/usr/bin/docker-compose -f $FIREFLY_HOME/docker-compose.yml up -d
ExecStop=/usr/bin/docker-compose -f $FIREFLY_HOME/docker-compose.yml down
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable firefly.service

log_success "Systemd service created"

log_success "Firefly installation completed!"
log_info "Next steps:"
log_info "1. Edit $FIREFLY_HOME/docker-compose.yml to set BESU_RPC_URL and other configs"
log_info "2. Set environment variables in /etc/systemd/system/firefly.service or .env file"
log_info "3. Start service: systemctl start firefly"
log_info "4. Firefly API will be available at: http://localhost:5000"

