"""
functions to deal with a temporary drive with 16 GB size
"""

import tempfile, re
from subprocess import call, Popen, PIPE

def create_drive(size = "16G"):
    """
    Create a temporary drive
    @param size the size of the drive as a string; "G" is meaning 1024^3
    @return a path to the loop device, and the underlying disk file
    """
    tmp = tempfile.NamedTemporaryFile(mode='wb', prefix="liveDrive-", delete=False)
    m = re.match(r"(\d+)G", size)
    if m:
        size = int(m.group(1))*(1024**3)
    else:
        size = 16*(1024**3)
    tmp.seek(size-1)
    tmp.write(bytes([0x0]))
    tmp.close()
    loop = ""
    # find the next loop's path
    with Popen(["/usr/sbin/losetup", "-f"], stdout=PIPE) as proc:
        loop = proc.stdout.read().decode("utf-8").strip()
    # setup the loop for the temporary file
    call(["/usr/sbin/losetup", "-f",tmp.name ])
    return loop, tmp.name

def loopDict(loop):
    """
    @param loop the path to a loop device
    @return a dictionary loop device => list of partitions
    """
    lines=[]
    with Popen(["/usr/sbin/sfdisk", "-l", loop], stdout=PIPE) as proc:
        lines = proc.stdout.read().decode("utf-8").split("\n")
    parts=[]
    for l in lines:
        m = re.match(r"^(/dev/loop[\d+]p[\d+]) .*", l)
        if m:
            parts.append(m.group(1))
    return {loop: parts}

def test_create_drive():
    loop, name = create_drive()
    print("created", loop, "=>", name)
    return


if __name__ == "__main__":
    test_create_drive()
    
