import os
import sys
import getpass
from uuid import uuid4


def build_config(user_name):
    template = '''
# WARNING: If you intend to restrict a user to only running the
# sshuttle command as root, THIS CONFIGURATION IS INSECURE.
# When a user can run sshuttle as root (with or without a password),
# they can also run other commands as root because sshuttle itself
# can run a command specified by the user with the --ssh-cmd option.

# INSTRUCTIONS: Add this text to your sudo configuration to run
# sshuttle without needing to enter a sudo password. To use this
# configuration, run 'visudo /etc/sudoers.d/sshuttle_auto' as root and
# paste this text into the editor that it opens. If you want to give
# multiple users these privileges, you may wish to use use different
# filenames for each one (i.e., /etc/sudoers.d/sshuttle_auto_john).

# This configuration was initially generated by the
# 'sshuttle --sudoers-no-modify' command.

Cmnd_Alias %(ca)s = /usr/bin/env PYTHONPATH=%(dist_packages)s %(py)s %(path)s *

%(user_name)s ALL=NOPASSWD: %(ca)s
'''

    content = template % {
        # randomize command alias to avoid collisions
        'ca': 'SSHUTTLE%(num)s' % {'num': uuid4().hex[-3:].upper()},
        'dist_packages': os.path.dirname(os.path.abspath(__file__))[:-9],
        'py': sys.executable,
        'path': sys.argv[0],
        'user_name': user_name,
    }

    return content


def sudoers(user_name=None):
    user_name = user_name or getpass.getuser()
    content = build_config(user_name)
    sys.stdout.write(content)
    exit(0)
