#!/usr/bin/env python2
# -*- coding: utf-8 -*-

####################

fifo_path = '/run/cron_tasks'

####################


import os, sys, re, stat


def drop_privileges(user):
	try: user, group = user.split(':')
	except ValueError: group = None

	try: user = int(user)
	except ValueError:
		import pwd
		try: user_pw = pwd.getpwnam(user)
		except KeyError:
			sys.stderr.write('User name not found: {}\n'.format(user))
			sys.exit(1)
		user = user_pw.pw_uid
		if group is None: group = user_pw.pw_gid
		else:
			try: group = int(group)
			except ValueError:
				import grp
				try: group = grp.getgrnam(group).gr_gid
				except KeyError:
					sys.stderr.write('Group name not found: {}\n'.format(group))
					sys.exit(1)

	os.setresgid(group, group, group)
	os.setresuid(user, user, user)


def main():
	try:
		svc = sys.argv[1]
		cmd = sys.argv[2:]
		if not cmd: raise IndexError
	except (ValueError, IndexError):
		sys.stderr.write('Usage: {} unit command args...\n'.format(sys.argv[0]))
		sys.exit(1)

	job = re.compile('^cron_(?P<user>[^_]+)_(?P<job>.*)\.service').search(svc)
	if not job:
		sys.stderr.write( 'Unrecognized service name format'
			' ("{}"), should be cron_<user>_<job>.service\n'.format(svc) )
		sys.exit(1)
	user, job = job.group('user', 'job')

	fifo = os.path.join(fifo_path, '{}_{}.fifo'.format(user, job))
	try: fifo_check = stat.S_ISFIFO(os.stat(fifo).st_mode)
	except OSError: fifo_check = False
	if not fifo_check:
		sys.stderr.write('WARNING: no FIFO socket for task output detected\n')
	else:
		from subprocess import Popen, PIPE, STDOUT
		tee = Popen(['tee', fifo], stdin=PIPE)
		os.dup2(tee.stdin.fileno(), 1)
		os.dup2(tee.stdin.fileno(), 2)

	if user != 'root': drop_privileges(user)

	os.execvp(cmd[0], cmd)


main()
