#!/usr/bin/python3
# -*- mode: python -*-

#   Copyright (c) 1999-2000  Jason Gunthorpe <jgg@debian.org>
#   Copyright (c) 2001-2003  James Troup <troup@debian.org>
#   Copyright (c) 2004  Joey Schulze <joey@infodrom.org>
#   Copyright (c) 2008,2009,2010 Peter Palfrader <peter@palfrader.org>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

from __future__ import print_function

import re
import time
import getopt
import sys
import os
import pwd
import email.header
import datetime

import ldap
from six.moves import input

from userdir_ldap.ldap import (
    TemplatesDir, GroupObjectClasses, BaseDn, UserObjectClasses, GenPass,
    EmailAppend, HostDomain, GetAttr, Group2GID, passwdAccessLDAP, HashPass,
    NameSplit, SplitEmail, ConfModule, IgnoreUsersForUIDNumberGen, BaseBaseDn)
import userdir_ldap.gpg as userdir_gpg

HavePrivateList = getattr(ConfModule, "haveprivatelist", True)
DefaultGroup = getattr(ConfModule, "defaultgroup", 'users')

# This tries to search for a free UID. There are two possible ways to do
# this, one is to fetch all the entires and pick the highest, the other
# is to randomly guess uids until one is free. This uses the former.
# Regrettably ldap doesn't have an integer attribute comparision function
# so we can only cut the search down slightly


def ShouldIgnoreID(uid):
   for i in IgnoreUsersForUIDNumberGen:
      try:
         if i.search(uid) is not None:
            return True
      except AttributeError:
         if uid == i:
            return True

   return False


# [JT] This is broken with Woody LDAP and the Schema; for now just
#      search through all UIDs.
def GetFreeID(lc):
   Attrs = lc.search_s(BaseBaseDn, ldap.SCOPE_SUBTREE,
                       "(|(uidNumber=*)(gidNumber=*))", ["uidNumber", "gidNumber", "uid"])
   HighestUID = 0
   gids = []
   uids = []
   for obj in Attrs:
      ID = int(GetAttr(obj, "uidNumber", "0"))
      uids.append(ID)
      gids.append(int(GetAttr(obj, "gidNumber", "0")))
      uid = GetAttr(obj, "uid", None)
      if ID > HighestUID and uid is not None and not ShouldIgnoreID(uid):
         HighestUID = ID

   resUID = HighestUID + 1
   while resUID in uids or resUID in gids:
      resUID += 1

   return (resUID, resUID)


# Main starts here
AdminUser = pwd.getpwuid(os.getuid())[0]

# Process options
ForceMail = 0
NoAutomaticIDs = 0
GuestAccount = False
OldGPGKeyRings = userdir_gpg.GPGKeyRings
userdir_gpg.GPGKeyRings = []
(options, arguments) = getopt.getopt(sys.argv[1:], "hgu:man")
for (switch, val) in options:
   if switch == '-h':
      print("Usage: ud-useradd <options>")
      print("Available options:")
      print("        -h         Show this help")
      print("        -u=<user>  Admin user (defaults to current username)")
      print("        -m         Force mail (for updates)")
      print("        -a         Use old keyrings instead (??)")
      print("        -n         Do not automatically assign UID/GIDs")
      print("        -g         Add a guest account")
      sys.exit(0)
   elif switch == '-u':
      AdminUser = val
   elif switch == '-m':
      ForceMail = 1
   elif switch == '-a':
      userdir_gpg.GPGKeyRings = OldGPGKeyRings
   elif switch == '-n':
      NoAutomaticIDs = 1
   elif switch == '-g':
      GuestAccount = True

lc = passwdAccessLDAP(BaseDn, AdminUser)

# Locate the key of the user we are adding
if GuestAccount:
   userdir_gpg.SetKeyrings(ConfModule.add_keyrings_guest.split(":"))
else:
   userdir_gpg.SetKeyrings(ConfModule.add_keyrings.split(":"))

while True:
   Foo = input("Who are you going to add (for a GPG search)? ")
   if Foo == "":
      sys.exit(0)

   Keys = userdir_gpg.GPGKeySearch(Foo)

   if len(Keys) == 0:
      print("Sorry, that search did not turn up any keys.")
      print("Has it been added to the Debian keyring already?")
      continue
   if len(Keys) > 1:
      print("Sorry, more than one key was found, please specify the key to use by\nfingerprint:")
      for i in Keys:
         userdir_gpg.GPGPrintKeyInfo(i)
      continue

   print()
   print("A matching key was found:")
   userdir_gpg.GPGPrintKeyInfo(Keys[0])
   break

# Crack up the email address from the key into a best guess
# first/middle/last name
Addr = SplitEmail(Keys[0][2])
cn, mn, sn = NameSplit(re.sub('["]', '', Addr[0]))
emailaddr = Addr[1] + '@' + Addr[2]
account = Addr[1]

privsub = emailaddr
gidNumber = 0
uidNumber = 0

Update = 0
Attrs = lc.search_s(BaseDn, ldap.SCOPE_ONELEVEL, "keyFingerPrint=" + Keys[0][1])
if len(Attrs) != 0:
   print("*** This key already belongs to", GetAttr(Attrs[0], "uid"))
   account = GetAttr(Attrs[0], "uid")
   Update = 1

# Try to get a uniq account name
while 1:
   if Update == 0:
      Res = input("Login account [" + account + "]? ")
      if Res != "":
         account = Res
   Attrs = lc.search_s(BaseDn, ldap.SCOPE_ONELEVEL, "uid=" + account)
   if len(Attrs) == 0:
      privsub = "%s@debian.org" % account
      break
   Res = input("That account already exists, update [No/yes]? ")
   if Res.lower() in ["yes", "y"]:
      # Update mode, fetch the default values from the directory
      Update = 1
      privsub = GetAttr(Attrs[0], "privateSub")
      gidNumber = GetAttr(Attrs[0], "gidNumber")
      uidNumber = GetAttr(Attrs[0], "uidNumber")
      emailaddr = GetAttr(Attrs[0], "emailForward")
      cn = GetAttr(Attrs[0], "cn")
      sn = GetAttr(Attrs[0], "sn")
      mn = GetAttr(Attrs[0], "mn")
      if privsub is None or privsub == "":
         privsub = " "
      break
   else:
      print("Aborting")
      sys.exit(1)

# Prompt for the first/last name and email address
Res = input("First name [" + cn + "]? ")
if Res != "":
   cn = Res
Res = input("Middle name [" + mn + "]? ")
if Res == " ":
   mn = ""
elif Res != "":
   mn = Res
Res = input("Last name [" + sn + "]? ")
if Res != "":
   sn = Res
Res = input("Email forwarding address [" + emailaddr + "]? ")
if Res != "":
   emailaddr = Res

# Debian-Private subscription
if HavePrivateList and not GuestAccount:
   Res = input("Subscribe to debian-private (space is none) [" + privsub + "]? ")
   if Res != "":
      privsub = Res
else:
   privsub = " "


(uidNumber, generatedGID) = GetFreeID(lc)
if not gidNumber:
   gidNumber = generatedGID

UserGroup = 1
if NoAutomaticIDs:
   # UID
   if not Update:
      Res = input("User ID Number [%s]? " % (uidNumber))
      if Res != "":
         uidNumber = Res

   # GID
   Res = input("Group ID Number (new usergroup is %s) [%s]" % (generatedGID, gidNumber))
   if Res != "":
      if Res.isdigit():
         gidNumber = int(Res)
      else:
         gidNumber = Group2GID(lc, Res)

   if gidNumber != generatedGID:
      UserGroup = 0

if GuestAccount:
  supplementaryGid = 'guest'
else:
  supplementaryGid = DefaultGroup

shadowExpire = None
hostacl = []
if GuestAccount:
   res = input("Expires in xx days [60] (0 to disable)")
   if res == "":
      res = '60'
   exp = int(res)
   if exp > 0:
      shadowExpire = int(time.time() / 3600 / 24) + exp
   res = input("Hosts to grant access to: ")
   for h in res.split():
      if '.' not in h:
         h = h + '.' + HostDomain
      if exp > 0:
         h = h + " " + datetime.datetime.fromtimestamp(time.time() + exp * 24 * 3600).strftime("%Y%m%d")
      hostacl.append(h)


# Generate a random password
if Update == 0 or ForceMail == 1:
   Password = input("User's Password (Enter for random)? ")

   if Password == "":
      print("Randomizing and encrypting password")
      Password = GenPass()
      Pass = HashPass(Password)

      # Use GPG to encrypt it, pass the fingerprint to ID it
      CryptedPass = userdir_gpg.GPGEncrypt(u"Your new password is '" + Password + "'\n",
                                           "0x" + Keys[0][1])
      Password = None
      if CryptedPass is None:
        raise Exception("Password Encryption failed")
   else:
      Pass = HashPass(Password)
      CryptedPass = "Your password has been set to the previously agreed value."
else:
   CryptedPass = ""
   Pass = None

# Now we have all the bits of information.
if mn != "":
   FullName = "%s %s %s" % (cn, mn, sn)
else:
   FullName = "%s %s" % (cn, sn)
print("------------")
print("Final information collected:")
print(" %s <%s@%s>:" % (FullName, account, EmailAppend))
print("   Assigned UID:", uidNumber, " GID:", gidNumber)
print("   supplementary group:", supplementaryGid)
print("   Email forwarded to:", emailaddr)
if HavePrivateList:
   print("   Private Subscription:", privsub)
print("   GECOS Field: \"%s,,,,\"" % FullName)
print("   Login Shell: /bin/bash")
print("   Key Fingerprint:", Keys[0][1])
if shadowExpire:
   print("   ShadowExpire: %d (%s)" % (shadowExpire, datetime.datetime.fromtimestamp(shadowExpire * 24 * 3600).strftime("%Y%m%d")))
for h in hostacl:
   print("   allowedHost: ", h)

Res = input("Continue [No/yes]? ")
if Res.lower() not in ["yes", "y"]:
   print("Aborting")
   sys.exit(1)

# Initialize the substitution Map
Subst = {}

encrealname = str(email.header.Header(FullName, 'utf-8', 200))

Subst["__ENCODED_REALNAME__"] = encrealname
Subst["__REALNAME__"] = FullName
Subst["__WHOAMI__"] = pwd.getpwuid(os.getuid())[0]
Subst["__DATE__"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime(time.time()))
Subst["__LOGIN__"] = account
Subst["__PRIVATE__"] = privsub
Subst["__EMAIL__"] = emailaddr
Subst["__PASSWORD__"] = CryptedPass

# Submit the modification request
Dn = "uid=" + account + "," + BaseDn
print("Updating LDAP directory..", end="")
sys.stdout.flush()

if Update == 0:
   # New account
   Details = [("uid", account.encode("utf-8")),
              ("objectClass", [c.encode("ascii") for c in UserObjectClasses]),
              ("uidNumber", str(uidNumber).encode("ascii")),
              ("gidNumber", str(gidNumber).encode("ascii")),
              ("supplementaryGid", supplementaryGid.encode("utf-8")),
              ("gecos", FullName.encode("utf-8") + b",,,,"),
              ("loginShell", b"/bin/bash"),
              ("keyFingerPrint", Keys[0][1].encode("ascii")),
              ("cn", cn.encode("utf-8")),
              ("sn", sn.encode("utf-8")),
              ("emailForward", emailaddr.encode("utf-8")),
              ("shadowLastChange", str(int(time.time() / 24 / 60 / 60)).encode("ascii")),
              ("shadowMin", b"0"),
              ("shadowMax", b"99999"),
              ("shadowWarning", b"7"),
              ("userPassword", b"{crypt}" + Pass.encode("ascii"))]
   if mn:
      Details.append(("mn", mn.encode("utf-8")))
   if privsub != " ":
      Details.append(("privateSub", privsub.encode("utf-8")))
   if shadowExpire:
      Details.append(("shadowExpire", str(shadowExpire).encode("utf-8")))
   if len(hostacl) > 0:
      Details.append(("allowedHost", [acl.encode("ascii") for acl in hostacl]))

   lc.add_s(Dn, Details)

   # Add user group if needed, then the actual user:
   if UserGroup == 1:
      Dn = "gid=" + account + "," + BaseDn
      lc.add_s(Dn, [("gid", account.encode("utf-8")), ("gidNumber", str(gidNumber).encode("ascii")), ("objectClass", [c.encode("ascii") for c in GroupObjectClasses])])
else:
   # Modification
   Rec = [(ldap.MOD_REPLACE, "uidNumber", str(uidNumber).encode("ascii")),
          (ldap.MOD_REPLACE, "gidNumber", str(gidNumber).encode("ascii")),
          (ldap.MOD_REPLACE, "gecos", FullName.encode("utf-8") + b",,,,"),
          (ldap.MOD_REPLACE, "loginShell", b"/bin/bash"),
          (ldap.MOD_REPLACE, "keyFingerPrint", Keys[0][1].encode("ascii")),
          (ldap.MOD_REPLACE, "cn", cn.encode("utf-8")),
          (ldap.MOD_REPLACE, "mn", mn.encode("utf-8")),
          (ldap.MOD_REPLACE, "sn", sn.encode("utf-8")),
          (ldap.MOD_REPLACE, "emailForward", emailaddr.encode("utf-8")),
          (ldap.MOD_REPLACE, "shadowLastChange", str(int(time.time() / 24 / 60 / 60)).encode("ascii")),
          (ldap.MOD_REPLACE, "shadowMin", b"0"),
          (ldap.MOD_REPLACE, "shadowMax", b"99999"),
          (ldap.MOD_REPLACE, "shadowWarning", b"7"),
          (ldap.MOD_REPLACE, "shadowInactive", b""),
          (ldap.MOD_REPLACE, "shadowExpire", b"")]
   if privsub != " ":
      Rec.append((ldap.MOD_REPLACE, "privateSub", privsub.encode("utf-8")))
   if Pass is not None:
      Rec.append((ldap.MOD_REPLACE, "userPassword", b"{crypt}" + Pass.encode("ascii")))
   # Do it
   lc.modify_s(Dn, Rec)

print()

# Abort email sends for an update operation
if Update == 1 and ForceMail == 0:
   print("Account is not new, Not sending mails")
   sys.exit(0)

# Send the Welcome message
print("Sending Welcome Email")
templatepath = TemplatesDir + "/welcome-message-%s" % supplementaryGid
if not os.path.exists(templatepath):
   templatepath = TemplatesDir + "/welcome-message"
Reply = userdir_gpg.TemplateSubst(Subst, open(templatepath, "r").read())
Child = os.popen("/usr/sbin/sendmail -t", "w")
# Child = os.popen("cat", "w")
Child.write(Reply)
if Child.close() is not None:
   raise Exception("Sendmail gave a non-zero return code")

# vim:set et:
# vim:set ts=3:
# vim:set shiftwidth=3:
