#!/bin/bash
#
# SOM Test eMMC Setup Script
# 
# Purpose: Pre-configure eMMC partitions and boot settings during SOM testing
# When to run: During SOM testing phase, when booted from SD card
# 
# This script generates U-Boot commands to:
# 1. Create GPT partition table on eMMC
# 2. Set eMMC boot configuration (PARTITION_CONFIG, BOOT_BUS_CONDITIONS)
# 
# After running this, production programming can use fast partition writes
# without triggering gpt write (which resets boot configuration).
#
# Usage:
#   1. Boot SOM from SD card
#   2. Interrupt U-Boot to get console prompt
#   3. Copy/paste the output commands from this script
#   OR
#   4. Save output to USB stick and run: source mmc 0:1 /setup.cmd
#

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TSV_FILE="${SCRIPT_DIR}/flashlayout_cargt-image-dev/optee/FlashLayout_emmc_stm32mp257f-cargt-00395-00365v3-optee.tsv"

if [ ! -f "$TSV_FILE" ]; then
    echo "ERROR: TSV file not found: $TSV_FILE"
    exit 1
fi

echo "=========================================="
echo "SOM Test - eMMC Setup Commands"
echo "=========================================="
echo ""
echo "Copy and paste these commands into U-Boot console:"
echo ""
echo "# Select eMMC device"
echo "mmc dev 1"
echo ""
echo "# Create GPT partition table"

# Parse TSV to extract partition definitions
# Format: Opt Id Name Type IP Offset Binary
# We need entries with PD or PED flags (partition define)

gpt_parts=""
part_num=1

while IFS=$'\t' read -r opt id name type ip offset binary; do
    # Skip comments and empty lines
    [[ "$opt" =~ ^#.*$ || -z "$opt" ]] && continue
    
    # Only process partition definitions (PD or PED flags)
    if [[ ! "$opt" =~ P ]]; then
        continue
    fi
    
    # Skip RAM-only loads (no partition write)
    if [[ "$opt" == "-" ]]; then
        continue
    fi
    
    # Extract partition info
    # Type format: "RawImage" or filesystem type
    # IP format: "mmc1" (we want mmc1 = eMMC)
    # Offset format: "0x00004400" (512-byte sectors, divide by 0x200)
    
    if [[ "$ip" != "mmc1" ]]; then
        continue
    fi
    
    # Convert offset to sectors (divide by 512 = 0x200)
    offset_dec=$((offset))
    sector_start=$((offset_dec / 512))
    
    # Determine partition size based on name
    # Note: This is approximate - adjust based on your actual layout
    case "$name" in
        "metadata1"|"metadata2")
            size_mb=1
            ;;
        "fip-a"|"fip-b")
            size_mb=4
            ;;
        "u-boot-env")
            size_mb=1
            ;;
        "bootfs")
            size_mb=64
            ;;
        "vendorfs")
            size_mb=16
            ;;
        "rootfs")
            size_mb=4096
            ;;
        "userfs")
            size_mb=16384  # Use remaining space
            ;;
        *)
            size_mb=1
            ;;
    esac
    
    size_sectors=$((size_mb * 1024 * 2))  # MB to 512-byte sectors
    
    # Build GPT partition string
    # Format: name=NAME,start=START,size=SIZE,type=TYPE
    if [ -n "$gpt_parts" ]; then
        gpt_parts="${gpt_parts};"
    fi
    
    # Determine partition type GUID
    case "$name" in
        "rootfs")
            type_guid="0FC63DAF-8483-4772-8E79-3D69D8477DE4"  # Linux filesystem
            ;;
        "bootfs"|"vendorfs"|"userfs")
            type_guid="0FC63DAF-8483-4772-8E79-3D69D8477DE4"  # Linux filesystem
            ;;
        *)
            type_guid="8DA63339-0007-60C0-C436-083AC8230908"  # Linux reserved
            ;;
    esac
    
    gpt_parts="${gpt_parts}name=${name},start=${sector_start},size=${size_sectors}"
    
    part_num=$((part_num + 1))
    
done < "$TSV_FILE"

if [ -z "$gpt_parts" ]; then
    echo "ERROR: No partition definitions found in TSV"
    exit 1
fi

echo "gpt write mmc 1 \"${gpt_parts}\""
echo ""
echo "# Set eMMC boot configuration"
echo "# PARTITION_CONFIG = 0x50 (boot from boot1/partition 2)"
echo "# BOOT_BUS_CONDITIONS = 0x00 (default)"
echo "mmc partconf 1 1 2 0"
echo "mmc bootbus 1 0 0 0"
echo ""
echo "# Verify configuration"
echo "mmc dev 1"
echo "mmc part"
echo ""
echo "# Save and continue"
echo "echo eMMC partitions created and boot config set"
echo ""
echo "=========================================="
echo "After running these commands:"
echo "1. Partitions are created on eMMC"
echo "2. Boot config is set correctly"
echo "3. Production programming can use fast writes"
echo "=========================================="
