#!/usr/bin/python3
# -*- mode: python -*-
# Checks the passwd file to make sure all entries are in the directory

from __future__ import print_function

import sys

import ldap

from userdir_ldap.ldap import connectLDAP, BaseDn


def PassCheck(lc, File, HomePrefix):
   F = open(File, "r")

   # Fetch all the users and generate a map out of them
   Attrs = lc.search_s(BaseDn, ldap.SCOPE_ONELEVEL, "uid=*",
                       ["uid", "uidNumber", "gidNumber", "loginShell"])
   UIDMap = {}
   for x in Attrs:
      if "uid" not in x[1]:
         continue
      UIDMap[x[1]["uid"][0].decode("utf-8")] = x[1]

   # Iterate over every user in the passwd file
   while(1):
      Line = F.readline()
      if Line == "":
         break

      Split = Line.split(":")
      if Split[0] not in UIDMap:
         print(Line, end="")
         continue

      Ats = UIDMap[Split[0]]
      Miss = []
      if "uidNumber" in Ats and Ats["uidNumber"][0].decode("ascii") != Split[2]:
         Miss.append("UID")
      if "gidNumber" in Ats and Ats["gidNumber"][0].decode("ascii") != Split[3]:
         Miss.append("GID")
      if "homeDirectory" in Ats and \
         Split[5] != HomePrefix + Split[0]:
         Miss.append("Home")
      if len(Miss) != 0:
         print("mismatch", Split[0], Miss)


# Connect to the ldap server
lc = connectLDAP()
lc.simple_bind_s("", "")

PassCheck(lc, sys.argv[1], sys.argv[2])
