#!/usr/local/bin/python

import sys
import os
import time
import getopt

def usage():
    print '''usage: %s [options] <file> <limit>
parameters:
    <file> is the output file for the log
    <limit> is the size limit of the log file (optional k, m, g suffix)
            When the log file reaches this limit, it will be renamed to
            <file>.bak and a new log started.
options:
    -h (--help): print this message
    -k (--keep): do not delete old backup files of the log.  Old log files
                 will have a time() style timestamp appended to prevent
                 overwrite.
''' % sys.argv[0]

def main():
    keep_backups = 0

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hk", ["help", "keep"])
    except getopt.GetoptError:
        usage()
        sys.exit(1)

    if len(args) == 2:
        file = args[0]
        limit = args[1]
    else:
        usage()
        sys.exit(1)
    
    for o, a in opts:
        if o in ('-k', '--keep'):
            keep_backups = 1

    if limit[-1].lower() == 'm':
        limit = int(limit[:-1]) * 1024 * 1024
    elif limit[-1].lower() == 'k':
        limit = int(limit[:-1]) * 1024
    elif limit[-1].lower() == 'g':
        limit = int(limit[:-1]) * 1024 * 1024 * 1024
    elif limit[-1].lower() == 'b':
        limit = int(limit[:-1])
    else:
        limit = int(limit)
    
    input_avail = 1
    while input_avail:
        if os.access(file, os.F_OK):
            if os.access(file + '.bak', os.F_OK):
                if keep_backups:
                    os.rename(file + '.bak', file + '.bak.%d' % time.time())
                else:
                    os.remove(file + '.bak')
            os.rename(file, file + '.bak')
        f = open(file, "a")
        while f and f.tell() < limit:
            txt = sys.stdin.readline(40)
            if not txt:
                input_avail = 0
                break
            f.write(txt)
        f.close()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
