#!/usr/bin/python
VERSION = '0.1'
import os, sys
from getopt import getopt, GetoptError
import ConfigParser
from subprocess import call
import ast

def usage():
    print '''
    Parameter:
    -f <pi.cfg file>
    -u <privacyidea user>
    -h : help
    '''


def fix_rights(file, user):

    # READ the configs
    conf = {}
    execfile(file, conf)

    # Create the user
    try:
        call("/usr/sbin/adduser  --system %s" % user, shell=True)
        print "Created user %s" % user
    except Exception, e:
        print "Failed to create user %s: %s" % (user, str(e))

    # fix the file itself!
    try:
        call("chmod 640 %s" % file, shell=True)
        call("chown %s:%s %s" % (user, "root", file), shell=True)
        print "Fixed access rights for %s" % file
    except Exception, e:
        print "Failed to fix access rights for %s" % file

    # Fix the encryption file
    try:
        call("chmod 400 %s" % conf.get("PI_ENCFILE"), shell=True)
        call("chown %s %s" % (user, conf.get("PI_ENCFILE")), shell=True)
        print "Fixed access rights for %s" % conf.get("PI_ENCFILE")
    except Exception, e:
        print "Failed to fix access rights for %s" % conf.get("PI_ENCFILE")

    # fix the audit key
    try:
        call("chmod 400 %s" % conf.get("PI_AUDIT_KEY_PRIVATE"), shell=True)
        call("chown %s %s" % (user, conf.get("PI_AUDIT_KEY_PRIVATE")), shell=True)
        print "Fixed access rights for %s" % conf.get("PI_AUDIT_KEY_PRIVATE")
    except Exception, e:
        print "Failed to fix access rights for %s" % conf.get("PI_AUDIT_KEY_PRIVATE")

    # TODO: logfile


def main():

    file = ""
    user = ""
    try:
        opts, args = getopt(sys.argv[1:], "f:u:h", ["file=", "user=", "help"])

    except GetoptError:
        print "There is an error in your parameter syntax:"
        usage()
        sys.exit(1)

    for opt, arg in opts:
        if opt in ('-f', '--file'):
            file = arg
        elif opt in ('-h', '--help'):
            usage()
            sys.exit(1)
        elif opt in ('-u', '--user'):
            user = arg

    if file and user:
        fix_rights(file, user)
    else:
        usage()
        sys.exit(2)

if __name__ == '__main__':
    main()
