#!/usr/bin/env python

import grp
import pwd
from systematic.shell import Script, ScriptCommand
from systematic.user import UnixPasswordDB, DatabaseError

USAGE = """Get command for OS/X

Very basic implementation of getent command for OS/X
"""


class GetEntCommand(ScriptCommand):
	def __init__(self, *args, **kwargs):
		super(GetEntCommand, self).__init__(*args, **kwargs)
		self.accounts = UnixPasswordDB()


class PasswdCommand(GetEntCommand):
	def print_user(self, user):
		return self.message(':'.join([
			'{}'.format(user.username),
			'{}'.format(user.password),
			'{}'.format(user.uid),
			'{}'.format(user.gid),
			'{}'.format(user.gecos),
			'{}'.format(user.directory),
			'{}'.format(user.shell),
		]))

	def run(self, args):
		self.accounts.load_users()

		if args.names:
			for name in args.names:
				try:
					self.print_user(self.accounts.lookup_user(name))
				except DatabaseError:
					pass

		else:
			for user in self.accounts.users:
				self.print_user(user)


class GroupCommand(GetEntCommand):
	def print_group(self, group):
		self.message(':'.join([
			'{}'.format(group.name),
			'{}'.format(group.password),
			'{}'.format(group.gid),
			','.join(group.member_uids),
		]))

	def run(self, args):
		self.accounts.load_groups()
		if args.names:
			for name in args.names:
				try:
					self.print_group(self.accounts.lookup_group(name))
				except DatabaseError:
					pass
		else:
			for group in self.accounts.groups:
				self.print_group(group)

script = Script(USAGE)

c = script.add_subcommand(PasswdCommand('passwd', 'Lookup users'))
c.add_argument('names', nargs='*', help='Names to lookup')

c = script.add_subcommand(GroupCommand('group', 'Lookup groups'))
c.add_argument('names', nargs='*', help='Names to lookup')

args = script.parse_args()
