#!/usr/bin/env python

# This script will create a group of users all at once based on an input file.
# The input file should contain the users in the following format, one per line:
# user,email,fullname
#
# Run as python createusers.py userlist.csv <instance>
# Instance defaults to 1 if not passed in.

import sys
import os
import re
from subprocess import *
import shutil
import setpass
import platform
import sdputils

if len(sys.argv) > 2:
  SDP_INSTANCE = str(sys.argv[2])
else:
  SDP_INSTANCE = '1'

utils = sdputils.SDPUtils(SDP_INSTANCE)
p4 = utils.p4
utils.login()

def loadconfig():
  user = ()
  users = []
  
  usersfile = sys.argv[1]
  
  usersfile = open(usersfile, "r")

  for line in usersfile.readlines():
    user = (re.match("^(.*),(.*),(.*)", line).groups())
#    log("DEBUG", "User %s added." % (user[0]))
    users.append(user)

  if users == []:
    log("ERROR", "No users found in config file.")

  usersfile.close()
  return users

def log(msglevel="DEBUG", message=""):
  if msglevel == "ERROR":
    print(message)
    sys.exit(1)
  else:
    print(message)

def runp4cmd(cmd):
  try:
    pipe = Popen(p4 + cmd, shell=True, stdin=PIPE, stdout=PIPE, universal_newlines=True)
    stdout, stderr = pipe.communicate()
    log("DEBUG", stdout)
    if pipe.returncode != 0:
      log("ERROR", "%s%s generated the following error: %s" % (p4, cmd, stderr))
    else:
      return stdout
  except OSError as err:
    log("ERROR", "Execution failed: %s" % (err))

def process_servers(users):
  """
  Each user line contains three components as follows:
  user,email,full name
  """
  
  file = "user.txt"
  
  for user in users:
    userfile = open(file, "w")
    userfile.write("User:\t%s\nEmail:\t%s\nFullName:\t%s\n" % (user[0], user[1], user[2]))
    userfile.close()
    cmd = " user -f -i < user.txt"
    runp4cmd(cmd)
    os.remove(file)
#	Commented out setpass since most people are choosing to use AD now.
#    setpass.setpassword(user[0])

def main():
  if len(sys.argv) < 1:
    print("This program requires the file containing the list of users as a parameter.\nThe users file should contain 'username,email,full name' 1 per line.")
  users = loadconfig()
  process_servers(users)

if __name__ == "__main__":
  main()
