#!/usr/bin/python

import argparse
import sys
import commands
import os
import re
import os.path

# The program should be ran under root's privillege
def check_perm():
    uid = int(os.getuid())
    return uid == 0

# Parse args by argparse
def get_parser():
    parser = argparse.ArgumentParser(prog="searchCrontab", description="searchCrontab Example", \
        epilog="""
        Examples:
            sudo searchCrontab -h
            sudo searchCrontab --target "test.php"
            sudo searchCrontab --target "0 4" --raw --iplist /etc/iplist/iplist.all
        Created by cooltime""", add_help=True, prefix_chars='-', usage=None)

    # select some pieces to reuse
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
    parser.add_argument('-t', '--target', help='search target, a crontab, a time or others', \
        required=True, dest='target')
    parser.add_argument('-f', '--iplist', help='file specify the hosts(iplist), default is iplist.all', \
        default='/etc/iplist/iplist.all', dest='iplist')
    parser.add_argument('-r', '--raw', action='store_true', help='''whether search in a raw
        mode(just search from each (raw) line returned by `crontab -l`, including commented ones)''', \
        dest='is_raw', default=False)

    return parser

# Filter args
def parse_args():
    args = get_parser().parse_args()

    # do some judgement

    return args

# Gather crontabs of hosts in iplist file to a dict whose key is host ip
def get_crontabs(iplist, is_raw):
    ret_dict = {}
    command = ""
    if is_raw:
        command = "/usr/bin/pssh -i -l root -h " + iplist + ' "crontab -l"'
    else:
        command = "/usr/bin/pssh -i -l root -h " + iplist + ' "crontab -l | grep -vE \"^#\""'

    output = commands.getoutput(command)
    begin_pattern = re.compile('\[\d+\].*\[(SUCCESS|FAILURE)\] (\d+\.\d+\.\d+\.\d+)')

    host = ""
    for line in output.split('\n'):
        begin_match = begin_pattern.match(line)
        if begin_match:
            status = begin_match.group(1)
            ip = begin_match.group(2)
            host = ip
            ret_dict[host] = []
            continue

        ret_dict[host].append(line)

    return ret_dict

def get_target_crontab(crontab_dict, target_crontab):
    ret = []
    for host, crontabs in crontab_dict.items():
        for crontab in crontabs:
            if crontab.find(target_crontab) != -1:
                ret.append((host, crontab))

    return ret

if __name__ == '__main__':
    # Get BASE_DIR, and this file shold be in BASE_DIR/bin/this.py
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    if not check_perm():
        print "you should be root to run this program"
        sys.exit(1)

    # Parse command line arguments
    args = parse_args()

    targets = get_target_crontab(get_crontabs(args.iplist, args.is_raw), args.target)

    for target in targets:
        print target
