#!/usr/bin/python2

import sys
import subprocess
import getpass

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

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

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


def main():

    if not sys.argv[1:]:
        print 'usage: %s <command>' % sys.argv[0]
        exit(-1)

    # Let's try and run it right away and see what happens
    p = subprocess.Popen(['sudo', '-S'] + sys.argv[1:], stdin=subprocess.PIPE)
    p.communicate()

    # It ran!
    if not p.returncode:
        exit(0)

    # It didn't :( - let's lock this region now to avoid having multiple password boxes pop-up
    l = fmutex('pysudo.%s.lock' % getpass.getuser())

    # Try running it again (maybe another process authenticated... why ask for a password again?)
    p = subprocess.Popen(['sudo', '-S'] + sys.argv[1:], stdin=subprocess.PIPE)
    p.communicate()

    if not p.returncode:
        l.unlock()
        exit(0)

    # No we really need to ask for a password :(
    for i in range(0, 3):
        password = passwordbox('Please enter your password.', 'sudo', '')
        if password is None:
            exit(1)

        # Try it out with a password now!
        p = subprocess.Popen(['sudo', '-S', 'true'], stdin=subprocess.PIPE)
        p.communicate(input='%s\n' % password)

        # Did it work? Yes: let's do it!
        if not p.returncode:
            l.unlock()
            p = subprocess.Popen(['sudo', '-S'] + sys.argv[1:], stdin=subprocess.PIPE)
            p.communicate(input='%s\n' % password)
            exit(p.returncode)

    exit(2)

if __name__ == '__main__':
    main()
