fixup/makeGptPartitions.go

89 lines
2.1 KiB
Go

package main
import (
"fmt"
"io"
"os"
"go.wit.com/log"
"github.com/diskfs/go-diskfs"
"github.com/diskfs/go-diskfs/partition/gpt"
)
// make a default bootable GPT partition table
func makeDefaultGPT(devname string) error {
// Open disk
// disk, err := diskfs.Open(devname, diskfs.ReadWrite)
disk, err := diskfs.Open(devname, diskfs.WithOpenMode(diskfs.ReadWrite))
if err != nil {
log.Errorf("Failed to open disk: %v\n", err)
return err
}
file, err := os.Open(devname)
if err != nil {
log.Errorf("Failed to open file for size: %v\n", err)
return err
}
defer file.Close()
// Determine disk size via Seek
sizeBytes, err := file.Seek(0, io.SeekEnd)
if err != nil {
log.Errorf("Failed to determine disk size: %v\n", err)
return err
}
sectorSize := int64(512)
totalSectors := uint64(sizeBytes / sectorSize)
// Setup partitions:
// Partition 1: BIOS boot, ~1MiB, starts at sector 2048
biosStart := uint64(2048)
biosSize := uint64(1 * 1024 * 1024) // bytes
biosSectors := biosSize / uint64(sectorSize)
// Partition 2: rest of the disk
rootStart := biosStart + biosSectors
rootSectors := totalSectors - rootStart
table := &gpt.Table{
LogicalSectorSize: int(sectorSize),
PhysicalSectorSize: int(sectorSize),
ProtectiveMBR: true,
Partitions: []*gpt.Partition{
{
Start: biosStart,
End: biosStart + biosSectors - 1,
// Size is optional, but let's provide it
Size: biosSectors * uint64(sectorSize),
// GUID for BIOS boot partition (ESP-like GUID for BIOS boot)
Type: biosBootGUID,
Name: "bios_grub",
},
{
Start: rootStart,
End: totalSectors - 1,
Size: rootSectors * uint64(sectorSize),
// GUID for Linux filesystem partition
Type: linuxFSGUID,
Name: "root",
},
},
}
if err := disk.Partition(table); err != nil {
log.Errorf("Failed to write GPT partition table: %v", err)
return err
}
fmt.Println("Partition table successfully written!")
return nil
}
// GUID definitions (copied from GPT standard tables)
const (
biosBootGUID = "21686148-6449-6E6F-744E-656564454649" // BIOS boot
linuxFSGUID = "0FC63DAF-8483-4772-8E79-3D69D8477DE4" // Linux filesystem
)