#!/usr/bin/env python2

import re
import sys
from subprocess import Popen

JOB_EXECUTER_FILE_CONFIG='/opt/opengnsys/job_executer/config.py'
BROWSER_FILE_CONFIG='/etc/init/tty1.conf'
BROWSER_PATH='/opt/opengnsys/bin/browser'
MENU_URL='/plugin/bootmenu/view'

def get_vars_from_line(line):
    return dict( [i.split('=',1) for i in line.split() if "=" in i] )


def set_default_values(dic):
    if 'nfsroot' not in dic:
        raise Exception("No nfsroot")

    if 'ogserver' not in dic:
        raise Exception("No ogserver")

    dic['ogimg'] = '/opt/opengnsys/images'

    samba_re = re.compile(r'^//([^/]*)/')
    nfs_re = re.compile(r'^([^/:]*):')

    if 'ogboot' not in dic:
        dic['ogboot'] = 'user'
    elif dic['ogboot'] not in ('user','admin'):
        dic['ogboot'] = 'user'

    if dic['ogboot'] == 'admin':
        dic['mount_opts'] = 'rw,'
    else:
        dic['mount_opts'] = 'ro,'

    if 'ogoffline' not in dic:
        dic['ogoffline'] = 'false'
    elif dic['ogoffline'] not in ('true','false'):
        dic['ogoffline'] = 'false'

    if samba_re.match(dic['nfsroot']):
        dic['ogprotocol'] = 'cifs'
        dic['mount_opts'] += 'serverino,acl,username=opengnsys,password=og'
        dic['ogrepo'] = samba_re.findall(dic['nfsroot'])[0]
    elif nfs_re.match(dic['nfsroot']):
        dic['ogprotocol'] = 'nfs'
        dic['mount_opts'] += 'nolock'
        dic['ogrepo'] = nfs_re.findall(dic['nfsroot'])[0]
    else:
        raise Exception('Unknown protocol')

    return dic


def get_mount_command(dic):
    command = []

    if dic['ogprotocol'] == 'cifs':
        # Adding mount
        command.append('mount.cifs')

        # Adding remote mount point
        command.append('//'+dic['ogrepo']+dic['ogimg'])

    elif dic['ogprotocol'] == 'nfs':
        # Adding mount
        command.append('mount.nfs')
        
        # Adding remote mount point
        command.append(dic['ogrepo']+':'+dic['ogimg'])

    # Adding local mount point
    command.append(dic['ogimg'])

    # Adding options
    command.append('-o')
    command.append(dic['mount_opts'])

    return command

def set_config_job_executer(server, config_file=JOB_EXECUTER_FILE_CONFIG):
    configuration = ""
    config_re=re.compile(r' *server_daemon_ip *=')
    with open(config_file) as f:
        for line in f:
            if config_re.match(line):
                configuration += 'server_daemon_ip = "' + server + '"\n'
            else:
                configuration += line

    return configuration

def get_browser_command(server):
    command = ""
    command += 'exec '
    command += BROWSER_PATH
    command += ' -qws'
    command += ' http://' + server + MENU_URL

    return command

if __name__ == '__main__':
    if sys.argv[1] != 'start':
        exit(-1)

    procline = ""
    with open('/proc/cmdline') as f:
       cmdline = f.read()

    dic = get_vars_from_line(cmdline)
    dic = set_default_values(dic)
    config_file = set_config_job_executer(dic['ogserver'])
    with open('/opt/opengnsys/job_executer/job_executer.py', 'w') as f:
        f.write(config_file)

    command = get_browser_command(dic['ogserver'])
    with open('/etc/init/tty1.conf', 'a') as f:
        f.write(command)

    p = Popen(get_mount_command(dic))
    return_code = p.wait()
    if return_code != 0:
        sys.stderr.write('Error montando el repositorio de imagenes')
