#!/usr/bin/python
#
# Turn partition table (msdos or GPT) into a shell script with parted
#
# Copyright (C) 2010 EDF SA
#
# Released under GPL v2+
#
# Julien BLACHE <julien-externe.blache@edf.fr>
#

import sys
import parted

disk = parted.Disk(parted.Device(sys.argv[1]))

print "#!/bin/sh"
print "set -e"
print ""
print "test -z \"$1\" && exit 1"
print
print "parted -s $1 mklabel %s" % disk.type
print "parted -s $1 mklabel %s" % disk.type

for part in disk.partitions:
	if part.type not in (parted.PARTITION_NORMAL, parted.PARTITION_EXTENDED, parted.PARTITION_LOGICAL):
		continue

	if part.fileSystem:
		if part.fileSystem.type.startswith("linux-swap"):
			fs = part.fileSystem.type
		else:
			fs = ""
			print "# Filesystem: %s" % part.fileSystem.type
	else:
		fs = ""

	if part.type == parted.PARTITION_NORMAL:
		ptype = "primary"
	elif part.type == parted.PARTITION_EXTENDED:
		ptype = "extended"
	elif part.type == parted.PARTITION_LOGICAL:
		ptype = "logical"

	start = part.geometry.start * disk.device.sectorSize
	end = start + part.getSize("b") - 1

	print "parted -s $1 mkpart %s \"%s\" %dB %dB" % (ptype, fs, start, end)

	if part.getFlag(parted.PARTITION_BOOT):
		print "parted -s $1 set %d boot on" % part.number

	if part.getFlag(parted.PARTITION_RAID):
		print "parted -s $1 set %d raid on" % part.number

	if part.getFlag(parted.PARTITION_BIOS_GRUB):
		print "parted -s $1 set %d bios_grub on" % part.number

