#!/usr/bin/env python

import os, os.path, sys, getpass, shlex, subprocess


  
def runprog(argv):
  pipe = False
  for i in range (len(argv)-1):
    if (argv[i] =='|'):
      pipe = True
      progSource = argv[:i]
      progDest = argv[(i+1):]
      
  if pipe:
      try:
        p1 = subprocess.Popen(progSource, stdout=subprocess.PIPE)
	subprocess.call(progDest,stdin=progSource.stdout,stdout=sys.stdout)
      # in case there is no pipe
      except ValueError:
	exeInOut()
  else:
    std_out = sys.stdin
    std_in = sys.stdin
    if (len(argv) > 2):
      if (argv[-2] == '>'):
	std_out = open(argv[-1],'w')
	argv = argv[:-2]
      if (argv[-2] == '<'):
	std_in = open(argv[-1],'r')
	argv = argv[:-2]
    subprocess.call(argv, stdin = std_in, stdout = std_out)
    
  return 

  
  
  
home=os.getenv('HOME')

def getcwd():
    "like os.getcwd(), but collapses the home directory prefix into ~"
    cwd = os.getcwd()
    if cwd.startswith(home):
        cwd = '~'+cwd[len(home):]
    return cwd

while True:
    print "%s@%s>" % (getpass.getuser(), getcwd()),

    argv = None
    try:
        argv = shlex.split(raw_input())
    except EOFError:
        print
        break                             # end of file from user, e.g. Ctrl-D

    if not argv:
        continue # empty command

    if argv[0] in ['exit', 'quit', 'bye']:
        break
    elif argv[0]=='cd':
        try:
            os.chdir(os.path.expanduser(argv[1])) # expand ~ to home directory
        except IndexError:                   # no arguments, chdir to home dir
            os.chdir(home)
        except OSError, s:
            print >>sys.stderr, "chdir: %s" % s
    else:
      runprog(argv) #TODO to put varients
	#print "TODO: execute %s" % ' '.join(argv)
    #  except:
	#print("ERROR, SYSTEM WILL EXIT")
	#break

# goodbye message
goodbye = "have a good sunny day, see you back soon"
print "*"+"-"*(len(goodbye)+2)+"*"
print "| %s |" % goodbye
print "*"+"-"*(len(goodbye)+2)+"*"
