#!/usr/bin/env python

import os
import sys
import argparse

def join(config, *args):
    return os.path.join(config.cache_dir, *args)

def get_cache_filename(config):
    return join(config, config.name)

def get_cache(config):
    filename = get_cache_filename(config)
    with open(filename) as fp:
        for line in fp:
            print line,

def create_cache(config):
    from tempfile import NamedTemporaryFile as TempFile
    tempfile = TempFile(delete = False)
    for line in sys.stdin:
        tempfile.write(line)
    os.rename(tempfile.name, get_cache_filename(config))

def prepare(config):
    # expand cache dirs like: ~/.cache
    cache_dir = os.path.expanduser(config.cache_dir)
    config.cache_dir = cache_dir
    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        prog="cache",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-c', '--cache-dir', default='~/.cache',
        help="Folder to store cached stdout")
    parser.add_argument('name', nargs='?', default='1',
        help="Name of cached file to work with")
    config = parser.parse_args()
    prepare(config)

    is_stdin = not sys.stdin.isatty()
    if is_stdin:
        create_cache(config)
    else:
        get_cache(config)
