#!/usr/bin/env python

from canari.easygui import passwordbox
from canari.utils.fs import fmutex

from pexpect import spawn, EOF
from sys import argv, stderr
from os import execvp


__author__ = 'Nadeem Douba'
__copyright__ = 'Copyright 2012, Canari Project'
__credits__ = []

__license__ = 'GPL'
__version__ = '0.1'
__maintainer__ = 'Nadeem Douba'
__email__ = 'ndouba@gmail.com'
__status__ = 'Development'


def main():

    if len(argv) == 1:
        print 'usage: %s <command>' % argv[0]
        exit(-1)

    child = None

    try:
        l = fmutex('pysudo.lock')
        child = spawn('sudo -S echo start')
        while not child.expect(['Password:', 'start']):
            password = passwordbox('Please enter your password.', 'sudo', '')
            child.sendline(password)
        del l
        execvp('sudo', ['sudo'] + argv[1:])

    except EOF:
        stderr.write(child.before)
    except TypeError:
        stderr.write('Terminated.')
    except Exception, e:
        stderr.write(str(e))


if __name__ == '__main__':
    main()
