#!/usr/bin/python

import os
import sys
import subprocess




def hdd_img(partition_root, target, fs_type, bootloader_name):
    print("### Creating HDD_IMG")

    # echo "Dont forget to check the numbers of sectors for each file"
    # QM: what does that mean?
    
    if fs_type != "fat32" and fs_type != "ext2":
        print "*** Error: unsupported filesystem type:", fs_type
        sys.exit()
    
    if not(os.path.isdir(partition_root)):
        print "*** Error: Partition root is not a valid directory"
        sys.exit()
    
    
    print sys.argv[0], ": Target = %s, fs type = %s, Partition root = %s" % (target, fs_type, partition_root)
    
    if not os.path.isfile(bootloader_name):
        print "*** Error: bootloader file name invalid: %s" % (bootloader_name)
        sys.exit()
    
    # Remove current disk image if it exists, otherwise the creation fails
    if (os.path.isfile(target)):
        print "rm", target
        os.remove(target)
    
    size_bytes = 512000
    sector_size = 4096 # must be 512 Bytes for generic_leti platform
    sectors_per_cluster = 8
    boot_size = os.path.getsize(bootloader_name)
    
    sectors_boot = (boot_size / sector_size) + 1
    
    # reserved sector will begin from sector 2 and will contain the boot_loader code,
    # the kernel image and the architecture informations
    # We put the backup of VBR (MBR) at the end of the reserved sector
    offset = 2
    reserved_sectors = offset + sectors_boot + 1
    back_up_sector = reserved_sectors - 1 # last reserved sector
    
    print "# %d reserved sectors --> backup at back up sector %d" % (reserved_sectors, back_up_sector) 
    # the first two cluster are not in the data region
    # data_region_clusters=$cluster_size-2
    
    #create partition
    if fs_type == "fat32":
        cmd = ['mkfs.vfat', '-C', '-F', '32', '-f', '1',
                    '-r', '512',
                    '-R', str(reserved_sectors),
                    '-S', str(sector_size),
                    '-s', str(sectors_per_cluster),
                    '-b', str(back_up_sector),
                    '-i', 'f7120c4f',
                    '-n', 'hdd',
                    '-v', target, str(size_bytes)]
        print(subprocess.list2cmdline(cmd))
        subprocess.call(cmd)
        # copy root
        for dir_or_file in os.listdir(partition_root):
            cmd = ['mcopy', '-s', '-i', target, os.path.join(partition_root, dir_or_file), '::/']
            print(subprocess.list2cmdline(cmd))
            subprocess.call(cmd)
    
    else:
        cmd = ['mkfs.ext2', target]
        print(subprocess.list2cmdline(cmd))
        subprocess.call(cmd)
        
    # copy bootloader, arch-info (boot-info) and kernel-img in reserved sectors from sector 2
    print "# Inserting boot_loader at sector %d" % (offset)
          
    cmd = ['dd', 'bs=%d' % sector_size, 'seek=%d' % offset, 'count=%d' % sectors_boot, 'conv=notrunc', 'if=%s' % bootloader_name, 'of=%s' % target]
    print(subprocess.list2cmdline(cmd))
    subprocess.call(cmd)

    print "### End of HDD image generation"


if __name__ == '__main__':

    if len(sys.argv) != 5:
        print "Usage: %s path/to/partition/root <hdd-filename> <fs_type> <bootloader-filename>" % sys.argv[0] 
        sys.exit()
    
    partition_root = sys.argv[1]
    target = sys.argv[2] # hdd wanted filename 
    fs_type = sys.argv[3]
    bootloader_name = sys.argv[4]
    
    hdd_img(partition_root, target, fs_type, bootloader_name)

