#!/usr/bin/env python 

# save this script as "/usr/bin/alias2" and make it executable 

import os 
import sys 

id_string = "#This file was created by alias2. Do not edit it. It may be overwritten automatically."
config_file = ".config/alias2/alias2.config" 

home = os.getenv("HOME")
path = os.getenv("PATH")
if home + "/bin" not in path: 
	print "alias2: \"" + home + "/bin\" required to be in the $PATH environment variable "  
	sys.exit(2)
alias_cmd = "" 
for i in range(len(sys.argv)): 
	if i != 0: 
		alias_cmd = alias_cmd + sys.argv[i] + " "
alias = alias_cmd.split("=")[0].strip()
try: 
	aliased = alias_cmd.split("=")[1].strip()
except IndexError: 
	## to be done later: 
	# if (len(sys.argv) == 2):
	#	print_the_contents_of_alias2_config()
	# if (len(sys.argv) == 3): 
	#	if sys.argv[3] == "-a"
	#		print_the_contents_of_alias2_config()
	print "alias2: no equal sign in \"alias2 " + alias_cmd.strip() + "\"."
	sys.exit(2)
if not alias.replace("-","").isalnum(): 
	print "alias2: \"" + alias + "\" contains one or more awkward characters "   
	sys.exit(2) 
if alias.split(" ")[0] != alias: 
	print "alias2: " + alias + " cannot be alias2ed." 
	sys.exit(2)
if os.path.exists(home + "/bin/" + alias): 
	fhr = open(home + "/bin/" + alias, "r")
	contents = fhr.read() 
	fhr.close() 
	if not id_string in contents: 
		print "alias2: " + home + "/bin/" + alias + " exists. Remove it manually. "
		sys.exit(2)
fhw = open(home + "/bin/" + alias, "w") 
fhw.write("#!/bin/bash \n\n")
fhw.write(id_string + "\n\n")
fhw.write(aliased + ' "$@"' + " \n")
fhw.close() 
os.system("chmod +x " + home + "/bin/" + alias)
print "alias2: " + alias + " created as an alias2 script" 
if not os.path.exists(home + "/" + os.path.dirname(config_file)): 
	dir_list = os.path.dirname(config_file).split("/") 
	dir_processed = home  
	for i in dir_list: 
		dir_processed = dir_processed + "/" + i 
		try: 
			os.mkdir(dir_processed)
		except OSError: 
			pass 
try: 
	fhr = open(home + "/" + config_file, "r")
	contents = fhr.read()
	fhr.close() 
except IOError: 
	contents = "" 
line_by_line = contents.split("\n")
already_registered = 0 
for i in line_by_line: 
	if alias == i: 
		already_registered = 1 
if not already_registered: 
	fhw = open(home + "/" + config_file, "w") 
	fhw.write(contents + alias + "\n")
	fhw.close()
