#!/bin/bash
# Author: Steven Shiau <steven _at_ clonezilla org>
# Description: Program to convert partition table dumped from sfdisk between sectors 512 and 4096 (Universal GPT/MBR Version)
# License: GPL
# This file contains code generated by Google Gemini.

set -e

print_usage() {
    echo "Usage: $0 <mode> <input_file> <output_file>"
    echo "Modes: 512to4k | 4kto512"
    exit 1
}

if [ "$#" -ne 3 ]; then print_usage; fi

MODE=$1
INPUT=$2
OUTPUT=$3

process_geometry() {
    local ratio=$1
    local op=$2 
    local target_ss=$3

    echo "Processing conversion ($MODE)..."

    # 1. Update Header and clear output
    # We also update 'first-lba' and 'last-lba' for GPT disks
    grep -v "start=" "$INPUT" | sed "s/sector-size: [0-9]*/sector-size: $target_ss/g" > "$OUTPUT"

    # 2. Process Partitions
    grep "start=" "$INPUT" | while read -r line; do
        # Extract the device path (e.g., /dev/sda1)
        DEVICE=$(echo "$line" | cut -d: -f1)
        
        # Extract Start and Size using flexible whitespace matching
        START=$(echo "$line" | grep -oP 'start=\s*\K[0-9]+')
        SIZE=$(echo "$line" | grep -oP 'size=\s*\K[0-9]+')
        
        # Capture EVERYTHING after the size value, including the comma and spaces
        # This works for both GPT (type=, uuid=) and MBR (Id=, bootable)
        EXTRA=$(echo "$line" | grep -oP 'size=\s*[0-9]+,\s*\K.*')

        if [ "$op" == "div" ]; then
            # 512 -> 4k: Ensure alignment to 4k boundaries
            NEW_START=$(( (START + ratio - 1) / ratio ))
            NEW_SIZE=$(( SIZE / ratio ))
        else
            # 4k -> 512: Direct conversion
            NEW_START=$(( START * ratio ))
            NEW_SIZE=$(( SIZE * ratio ))
        fi

        # Reconstruct line. If EXTRA is empty, don't add the trailing comma.
        if [ -n "$EXTRA" ]; then
            NEW_LINE="$DEVICE: start=$NEW_START, size=$NEW_SIZE, $EXTRA"
        else
            NEW_LINE="$DEVICE: start=$NEW_START, size=$NEW_SIZE"
        fi
        
        echo "$NEW_LINE" >> "$OUTPUT"
    done
}

case "$MODE" in
    "512to4k") process_geometry 8 "div" 4096 ;;
    "4kto512") process_geometry 8 "mult" 512 ;;
    *) print_usage ;;
esac

echo "Success! Output saved to $OUTPUT"
