#!/usr/bin/python3

# Copyright (c) 2015 Peter Palfrader <peter@palfrader.org>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import print_function

import datetime
import argparse
import sys

import ldap

from userdir_ldap.ldap import connectLDAP, BaseBaseDn


def days(i):
    return datetime.timedelta(days=i)


parser = argparse.ArgumentParser(description='Query/Extend a guest account.')
parser.add_argument('uid', metavar='UID',
                    help="user's uid to be extended")
parser.add_argument('-x', '--extend', metavar='DAYS',
                    type=int,
                    const=90, nargs='?',
                    help="days to be extended")
args = parser.parse_args()
uid = args.uid

lc = connectLDAP()

x = lc.search_s(BaseBaseDn, ldap.SCOPE_SUBTREE, "uid=" + uid, [])
if len(x) == 0:
    print("No hit.", file=sys.stderr)
    sys.exit(1)
elif len(x) > 1:
    print("More than one hit!?", file=sys.stderr)
    sys.exit(1)


dn = x[0][0]
attrs = x[0][1]

keys = list(attrs)
keys.sort()
print("Current info:", file=sys.stderr)
print(dn, file=sys.stderr)
for a in keys:
    for i in attrs[a]:
        print("  {:<16}: {}".format(a, i.decode("utf-8")), file=sys.stderr)

if 'supplementaryGid' not in attrs or b'guest' not in attrs['supplementaryGid']:
    print("Account is not a guest-account,", file=sys.stderr)
    sys.exit(1)
if 'shadowExpire' not in attrs:
    print("Account does not expire.", file=sys.stderr)
    sys.exit(1)

epoch = datetime.date(1970, 1, 1)
shadowExpire = epoch + days(int(attrs['shadowExpire'][0].decode('ascii')))
allowedHost = {}
if 'allowedHost' in attrs:
    for entry in attrs['allowedHost']:
        entry = entry.decode('ascii')
        list = entry.split(None, 1)
        if len(list) == 1:
            continue
        (h, expire) = list
        try:
            parsed = datetime.datetime.strptime(expire, '%Y%m%d')
        except ValueError:
            print("Cannot parse expiry date in '%s' in hostACL entry." % entry, file=sys.stderr)
        allowedHost[h] = parsed


print(file=sys.stderr)
print("Unix account expires on %s." % shadowExpire, file=sys.stderr)
print("Allowed hosts: ", file=sys.stderr)
for h in sorted(allowedHost):
    print(" %s: %s" % (h, allowedHost[h].strftime('%Y-%m-%d')), file=sys.stderr)

if args.extend is None:
    print(file=sys.stderr)
    print("Use -x to extend account.", file=sys.stderr)
    sys.exit(0)

print("Extending for %d days" % args.extend, file=sys.stderr)

today = datetime.date.today()
until = today + days(args.extend)

print(file=sys.stderr)
print(file=sys.stderr)
print("dn:", dn)
print("changetype: modify")

print("replace: shadowLastChange")
print("shadowLastChange: %d" % (today - epoch).days)
print("-")

print("replace: shadowExpire")
print("shadowExpire: %d" % (until - epoch).days)
print("-")

print("replace: allowedHost")
for h in sorted(allowedHost):
    print("allowedHost: %s %s" % (h, until.strftime('%Y%m%d')))
print("-")
print()

print(file=sys.stderr)
print("Maybe paste (or pipe) this into", file=sys.stderr)
print("ldapmodify -ZZ -x -D uid=$USER,ou=users,dc=debian,dc=org -W -h db.debian.org", file=sys.stderr)

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