#!/bin/bash

set -e

echo "🧪 Testing sudo fix for file operations..."

# Create a test directory structure similar to the build environment
TEST_DIR="/tmp/test-sudo-fix"
ROOTFS_DIR="$TEST_DIR/rootfs/etc"
TEMP_DIR="/tmp/test-sudo-fix-temp"

echo "📁 Creating test directory structure..."
sudo rm -rf "$TEST_DIR" "$TEMP_DIR"
mkdir -p "$ROOTFS_DIR" "$TEMP_DIR"

# Set ownership to root:root (like in the build environment)
echo "🔐 Setting ownership to root:root for rootfs..."
sudo chown -R root:root "$TEST_DIR"

echo "👤 Current user: $(whoami)"
echo "📊 Directory ownership:"
ls -la "$TEST_DIR"

# Test 1: Direct file write (should fail)
echo -e "\n🧪 Test 1: Direct file write (should fail)..."
if echo "test content" > "$ROOTFS_DIR/test1.txt" 2>/dev/null; then
    echo "❌ Direct write succeeded (unexpected)"
else
    echo "✅ Direct write failed as expected (permission denied)"
fi

# Test 2: Sudo file write (should succeed)
echo -e "\n🧪 Test 2: Sudo file write (should succeed)..."
TEMP_FILE="$TEMP_DIR/temp_test2.txt"
echo "test content" > "$TEMP_FILE"
if sudo cp "$TEMP_FILE" "$ROOTFS_DIR/test2.txt"; then
    echo "✅ Sudo file write succeeded"
    sudo chmod 644 "$ROOTFS_DIR/test2.txt"
else
    echo "❌ Sudo file write failed"
    exit 1
fi

# Test 3: Sudo symlink creation (should succeed)
echo -e "\n🧪 Test 3: Sudo symlink creation (should succeed)..."
if sudo ln -sf "/usr/share/zoneinfo/UTC" "$ROOTFS_DIR/localtime"; then
    echo "✅ Sudo symlink creation succeeded"
else
    echo "❌ Sudo symlink creation failed"
    exit 1
fi

# Test 4: Verify files were created
echo -e "\n📋 Verifying created files..."
echo "Files in $ROOTFS_DIR:"
ls -la "$ROOTFS_DIR"

echo -e "\n🎉 All sudo tests passed! The fix should work."
echo "💡 The issue was that files were owned by root:root but the Go code"
echo "   was trying to write them directly as the current user."
echo "🔧 The solution is to use sudo for file operations in the rootfs."

# Cleanup
echo -e "\n🧹 Cleaning up..."
sudo rm -rf "$TEST_DIR" "$TEMP_DIR"
echo "✅ Cleanup completed"
