#!/usr/bin/env python

import os
import re
import subprocess as sc


TMPL_WIN = "/etc/huayra/grub/windows.tmpl"
TMPL_RECU = "/etc/huayra/grub/recuperacion.tmpl"


def blkid():
    """
    devuelve el output de `blkid`.
    params: none
    returns: list
    """
    blkid_output = sc.check_output("blkid", shell=True).split("\n")
    return filter(lambda x: x, blkid_output)


def parse_blkid(blkid_output):
    """
    le da formato al output de `blkid`.
    params: list
    returns: list of dict
    """
    regex_root = '(?P<root>.+): '
    regex_num = '([^\d+])'
    regex_label = '(LABEL="(?P<label>.[^"]+)")?( )?'
    regex_uuid = '(UUID="(?P<uuid>.[^"]+)")?( )?'
    regex_type = '(TYPE="(?P<type>.[^"]+)")?'
    regex_blkid = regex_root + regex_label + regex_uuid + regex_type

    tmp = []
    for blk in blkid_output:
        tmp.append(re.search(regex_blkid, blk))

    blkid_dict = {}
    for res in tmp:

        gpt = int(re.sub(regex_num, '', res.group('root')))

        blkid_dict[res.group('root')] = {'root': res.group('root'),
                                         'gpt': "gpt%d" % gpt,
                                         'label': res.group('label'),
                                         'uuid': res.group('uuid'),
                                         'type': res.group('type')}

    return blkid_dict


def gen_template(tmpl_name="", parttype='', blkid=None):
    """
    genera templates para grub
    params: str, dict
    returns: str
    """
    tmpl = ""
    if tmpl_name and parttype:

        data = [blkid[root] for root in blkid
                if blkid[root]['type'] == parttype]
        if len(data) > 0:
            data = data[0]

            tmpl_file = open(tmpl_name, 'r')
            tmpl = ''.join(tmpl_file.readlines())
            tmpl_file.close()

            tmpl = tmpl.format(**data)
            tmpl = tmpl.replace('OPENBRACKET', '{')
            tmpl = tmpl.replace('CLOSEBRACKET', '}')

    return tmpl


def main():
    """
    lee la salida de blkid, parsea los datos y genera los templates.
    params: nil
    returns: nil
    """
    blkid_output = blkid()
    blkid_output = parse_blkid(blkid_output)

    tmpl_win = gen_template(TMPL_WIN, 'vfat', blkid_output)
    tmpl_recu = gen_template(TMPL_RECU, 'ext2', blkid_output)

    print tmpl_win
    print tmpl_recu


if __name__ == "__main__":
    if os.getuid() == 0:
        main()
