#!/usr/bin/env python3
# vi:ft=python


"""
A simple command like `cron`, but more human friendly.

The default configuration file is /etc/schetab, syntax goes like:

    # (optional) set time zone first
    timezone = +0800

    # line starts with # is a comment
    every 60 minutes, echo "wubba lubba dub dub"

    # backup database every day at midnight
    every day at 00:00, mysqldump -u backup

    # redirect logs so you can see them
    every minute, do_some_magic >> /some/output/file 2>&1
"""

import argparse
import sys

import sche

parser = argparse.ArgumentParser(
    description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("-f", "--file", default="/etc/schetab", help="configuration file to use")
parser.add_argument("-t", "--test", action="store_true", help="test configuration and exit")
args = parser.parse_args()

try:
    with open(args.file) as f:
        schedule_lines = f.read()
except IOError:
    print("error reading file %s" % args.file)
    sys.exit(-1)

for line in schedule_lines.split("\n"):
    # ignore comments
    if line.startswith("#"):
        continue
    # ignore empty lines
    if not line.strip():
        continue
    # check timezone setting
    if line.startswith("timezone"):
        _, timezone_str = line.split("=")
        sche.timezone(timezone_str.strip())
        continue
    try:
        expr, command = line.split(",", 1)
    except ValueError:
        print("line '%s' is not valid" % line)
        sys.exit(-1)

    if not args.test:
        sche.when(expr).run_command(command, shell=True)

sche.run_forever()
