summaryrefslogtreecommitdiff
path: root/makeGptPartitions.go
blob: d272e7d492672864d0c176e24582857e8a065a3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
)