#!/bin/bash
set -euo pipefail

# Docker-based framebuffer testing for hdmistat

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $*"
}

error() {
    echo -e "${RED}[ERROR]${NC} $*" >&2
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $*"
}

# Create Dockerfile
create_dockerfile() {
    log "Creating Dockerfile for framebuffer testing..."
    
    cat > "${PROJECT_DIR}/Dockerfile.fbtest" << 'EOF'
FROM ubuntu:22.04

# Avoid interactive prompts
ENV DEBIAN_FRONTEND=noninteractive

# Install dependencies
RUN apt-get update && apt-get install -y \
    # Build tools
    build-essential \
    git \
    wget \
    golang-go \
    # Framebuffer tools
    fbset \
    fbi \
    # Virtual framebuffer
    xvfb \
    x11vnc \
    # System tools
    systemd \
    systemd-sysv \
    sudo \
    htop \
    procps \
    && rm -rf /var/lib/apt/lists/*

# Install Go 1.24.4 (ARM64 compatible)
RUN ARCH=$(dpkg --print-architecture) && \
    GO_ARCH=$([ "$ARCH" = "arm64" ] && echo "arm64" || echo "amd64") && \
    wget -q -O /tmp/go.tar.gz https://go.dev/dl/go1.24.4.linux-${GO_ARCH}.tar.gz && \
    rm -rf /usr/local/go && \
    tar -C /usr/local -xzf /tmp/go.tar.gz && \
    rm /tmp/go.tar.gz

ENV PATH="/usr/local/go/bin:${PATH}"
ENV GOPATH="/root/go"
ENV PATH="${GOPATH}/bin:${PATH}"

# Create virtual framebuffer on startup
RUN echo '#!/bin/bash\n\
Xvfb :99 -screen 0 1920x1080x24 &\n\
export DISPLAY=:99\n\
sleep 2\n\
x11vnc -display :99 -forever -nopw -quiet -shared -bg\n\
' > /usr/local/bin/start-vnc.sh && chmod +x /usr/local/bin/start-vnc.sh

# Copy hdmistat source
COPY . /hdmistat
WORKDIR /hdmistat

# Build hdmistat
RUN make build && \
    cp hdmistat /usr/local/bin/

# Create test script
RUN echo '#!/bin/bash\n\
echo "Starting virtual framebuffer..."\n\
/usr/local/bin/start-vnc.sh\n\
echo "VNC server started on port 5900"\n\
echo ""\n\
echo "Creating virtual framebuffer device..."\n\
# Note: In Docker, we cannot access real /dev/fb0\n\
# For testing, hdmistat can be modified to render to a file/image\n\
echo ""\n\
echo "Starting hdmistat in test mode..."\n\
hdmistat info\n\
echo ""\n\
echo "To test hdmistat daemon:"\n\
echo "  hdmistat daemon --framebuffer /tmp/fb0"\n\
echo ""\n\
echo "Note: Real framebuffer access requires --privileged mode"\n\
exec /bin/bash\n\
' > /test-hdmistat.sh && chmod +x /test-hdmistat.sh

# Expose VNC port
EXPOSE 5900

CMD ["/test-hdmistat.sh"]
EOF
}

# Create docker-compose file
create_compose() {
    log "Creating docker-compose configuration..."
    
    cat > "${PROJECT_DIR}/docker-compose.fbtest.yml" << 'EOF'
version: '3.8'

services:
  hdmistat-test:
    build:
      context: .
      dockerfile: Dockerfile.fbtest
    image: hdmistat-fbtest:latest
    container_name: hdmistat-fbtest
    # Uncomment for real framebuffer access (Linux only)
    # privileged: true
    # devices:
    #   - /dev/fb0:/dev/fb0
    ports:
      - "5900:5900"  # VNC port
    volumes:
      - .:/hdmistat:rw
      - /tmp/.X11-unix:/tmp/.X11-unix:rw
    environment:
      - DISPLAY=:99
    stdin_open: true
    tty: true
    # Uncomment for systemd support
    # command: /sbin/init
    # tmpfs:
    #   - /run
    #   - /run/lock
    #   - /tmp
    # volumes:
    #   - /sys/fs/cgroup:/sys/fs/cgroup:ro
EOF
}

# Create run script
create_run_script() {
    log "Creating run script..."
    
    cat > "${PROJECT_DIR}/run-docker-fbtest.sh" << 'EOF'
#!/bin/bash

echo "Building and starting hdmistat framebuffer test container..."
echo ""

# Build the container
docker-compose -f docker-compose.fbtest.yml build

# Run the container
echo "Starting container..."
echo "VNC will be available on localhost:5900"
echo ""

docker-compose -f docker-compose.fbtest.yml run --rm hdmistat-test

# Cleanup
echo ""
echo "Cleaning up..."
docker-compose -f docker-compose.fbtest.yml down
EOF
    chmod +x "${PROJECT_DIR}/run-docker-fbtest.sh"
}

# Create VNC helper
create_vnc_helper() {
    cat > "${PROJECT_DIR}/view-docker-vnc.sh" << 'EOF'
#!/bin/bash
echo "Connecting to VNC server in Docker container..."
echo "Make sure the container is running first!"
echo ""

# Try different VNC viewers
if command -v vncviewer &> /dev/null; then
    vncviewer localhost:5900
elif command -v open &> /dev/null; then
    open vnc://localhost:5900
else
    echo "No VNC viewer found"
    echo "Connect manually to: localhost:5900"
fi
EOF
    chmod +x "${PROJECT_DIR}/view-docker-vnc.sh"
}

# Print instructions
print_instructions() {
    echo ""
    echo "========================================"
    echo "Docker Framebuffer Test Setup Complete!"
    echo "========================================"
    echo ""
    echo "Three test environments have been created:"
    echo ""
    echo "1. QEMU Raspberry Pi (Full emulation):"
    echo "   ./scripts/qemu-rpi-test.sh"
    echo ""
    echo "2. QEMU with Alpine (Lightweight):"
    echo "   ./scripts/qemu-fb-test.sh"
    echo ""
    echo "3. Docker with virtual framebuffer:"
    echo "   ./run-docker-fbtest.sh"
    echo ""
    echo "For Docker testing:"
    echo "  - Easiest to set up"
    echo "  - Uses virtual framebuffer (Xvfb)"
    echo "  - View via VNC on port 5900"
    echo ""
    echo "For QEMU testing:"
    echo "  - More realistic framebuffer"
    echo "  - Full system emulation"
    echo "  - Better for final testing"
    echo ""
    warn "Note: Real framebuffer (/dev/fb0) testing requires:"
    warn "  - Linux host system"
    warn "  - Running with appropriate permissions"
    warn "  - Or using QEMU/real hardware"
}

# Main
main() {
    log "Setting up Docker framebuffer test environment..."
    
    create_dockerfile
    create_compose
    create_run_script
    create_vnc_helper
    print_instructions
    
    log "Setup complete!"
}

main "$@"