#!/usr/bin/env python
"""
Script that cats a file if first argument is a file, else if there is something in stdin print that,
else echo the script arguments

Flags
------------
-h : runs python help function on this file to print docstrings and functions

Examples
------------
~$ python cat_or_echo.py cat_or_echo.py
    prints this file

~$ python cat_or_echo.py < cat_or_echo.py
    prints this file

~$ python cat_or_echo.py This is a silly example
    prints "This is a silly example"
"""
import os,sys
from functools import reduce


def cat(filepath):
    """
    works like unix cat program, takes a file path reads the entire file and prints it
    note: the with code block is just an elegant assignment and close keyword.
          Basically, it makes sure the file doesn't stay open in memory
    """
    with open(filepath,"r") as fin:
        print(fin.read())
    #note: fin.read returns a string of the entire file, fin.readline reads a single line,
    #      and fin.readlines reads all lines as an array, you can read anything like this even binary

def printstdin():
    """
    prints stdin
    stdin is a object you can query for various things dir(sys.stdin) will print a list of all the things.
    note: dir works on anything in python, there is also a help function, help(thing) will print these strings
    """
    print(sys.stdin.read())

def echo():
    """
    prints arguments to script
    """
    #don't worry too much about this it just concatonates a bunch of strings in sys.argv which is an array that
    #contains everything after the word python in terminal when you run any file
    input_string = reduce(lambda x,y="": x+y, sys.argv[1:])
    print(input_string)

#Because any file can be read as a library so I can use the above subroutines elsewhere this if statement prevents
#this file executing as a script upon import
if __name__=="__main__": #everything in here will only be run if this file is used as a script not a library

    #parse flags
    if "-h" in sys.argv:
        help(__name__)

    #do stuff
    if len(sys.argv)>1 and os.path.isfile(sys.argv[1]): #second entry is thing after the name of this file in argv
        cat(sys.argv[1])
    elif not sys.stdin.isatty(): #tests that stdin has something to read
        printstdin()
    else:
        echo()