#!/bin/bash
# Test script for fbsimplestat in Linux VM
# Stops hdmistat service, syncs repo, builds and runs fbsimplestat

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"

echo -e "${YELLOW}Starting fbsimplestat test...${NC}"

# Stop hdmistat service if running
echo -e "${YELLOW}Checking hdmistat service...${NC}"
if systemctl is-active --quiet hdmistat 2>/dev/null; then
    echo -e "${YELLOW}Stopping hdmistat service...${NC}"
    sudo systemctl stop hdmistat
    echo -e "${GREEN}hdmistat service stopped${NC}"
else
    echo -e "${GREEN}hdmistat service not running${NC}"
fi

# Create target directory
echo -e "${YELLOW}Creating target directory...${NC}"
sudo rm -rf /tmp/hdmistat
mkdir -p /tmp/hdmistat

# Rsync repo to /tmp/hdmistat (excluding test directory)
echo -e "${YELLOW}Syncing repository to /tmp/hdmistat...${NC}"
rsync -av --progress \
    --exclude='test/' \
    --exclude='.git/' \
    --exclude='*.qcow2' \
    --exclude='*.iso' \
    --exclude='*.img' \
    --exclude='vendor/' \
    "$REPO_ROOT/" /tmp/hdmistat/

# Change to the synced directory
cd /tmp/hdmistat

# Build fbsimplestat
echo -e "${YELLOW}Building fbsimplestat...${NC}"
cd cmd/fbsimplestat
go build -v .

if [ ! -f ./fbsimplestat ]; then
    echo -e "${RED}Build failed: fbsimplestat binary not found${NC}"
    exit 1
fi

echo -e "${GREEN}Build successful!${NC}"

# Run fbsimplestat
echo -e "${YELLOW}Running fbsimplestat...${NC}"
echo -e "${YELLOW}Press Ctrl+C to exit${NC}"

# Try to run with framebuffer first, fall back to terminal if needed
if [ -e /dev/fb0 ] && [ -w /dev/fb0 ]; then
    echo -e "${GREEN}Running with framebuffer display${NC}"
    sudo ./fbsimplestat
else
    echo -e "${YELLOW}Running with terminal display${NC}"
    ./fbsimplestat
fi