#!/usr/bin/env python

import os
import sys

args = sys.argv[1:]
loc = os.path.dirname(__file__)

user = 'user'
if '-u' in args:
    user = args[args.index('-u')+1]

if '-l' in args:
    if user == 'error':
        raise ValueError("Delibrate IO Error")
    if not os.path.exists(os.path.join(loc, '%s.tab' % user)):
        sys.stderr.write("no crontab for %s\n" % user)
        sys.exit(1)
    fhl = open(os.path.join(loc, '%s.tab' % user), 'r')
    print(fhl.read())
else:
    for filename in args:
        if filename[0] == '-' or filename == user:
            continue
        new_name = os.path.join(loc, '%s.tab' % user)
        if not os.path.exists(filename):
            raise KeyError("Can't find file: %s" % filename)
        if os.path.exists(new_name):
            raise KeyError("Can't write file: %s, already exists" % new_name)
        with open(filename, 'r') as source:
            with open(new_name, 'w') as output:
                output.write(source.read())

sys.exit(0)
