#!/usr/bin/python
#  This script will build platform-specific dotfiles and create the appropriate symlinks in ~

import platform
import os
import io
import sys
sysName = ''
homeDir = ''
destDir = ''
bashOutputFile = ''
bashOutputDotFile = ''

def init():
  global homeDir
  global destDir

  homeDir = os.path.expanduser('~') + '/'
  destDir = os.path.dirname(os.path.abspath(__file__)) + '/'
  os.chdir(destDir)

def identifySystem():
  global sysName
  global bashOutputFile
  global bashOutputDotFile

  sysName = platform.system()
  if sysName != 'Linux' and sysName != 'Darwin':
    print "System not supported!"
    exit(1)
  else:
    print "System identified as " + sysName
  if sysName == 'Linux':
    bashOutputFile = 'bashrc'
  else:
    bashOutputFile = 'bash_profile'
  bashOutputDotFile = '.' + bashOutputFile

def cleanUp():
  print "Cleaning up output files in " + destDir + " ..."
  for file in [bashOutputFile,bashOutputDotFile]:
    if os.path.isfile(file):
      print "\tRemoving " + file
      os.remove(file)

def handleBashrcFileWrite(contents, isPrivateFile):
  with open(bashOutputDotFile,'a') as bashrc:
    bashrc.write(contents.getvalue())
  if not isPrivateFile:
    with open(bashOutputFile,'a') as bashrc:
      bashrc.write(contents.getvalue())

def addBashOutputFileHeader():
  print "Writing " + bashOutputFile + " file header..."
  with io.StringIO() as bashrc:
    bashrc.write(unicode("#!/bin/bash\n"))
    if sysName == 'Linux':
      bashrc.write(unicode("# ~/.bashrc: executed by bash(1) for non-login shells.\n"))
    elif sysName == 'Darwin':
      bashrc.write(unicode("# ~/.bash_profile: executed by bash(1) for lon-login shells.\n"))
    bashrc.write(unicode("# This file was generated by a script. Do not edit manually!\n"))
    handleBashrcFileWrite(bashrc, False)

def addInputFileContents(inputFile, allowComments, isPrivateFile):
  if hasattr(inputFile, 'name'):
    print "\t" + inputFile.name
  with io.StringIO() as bashrc:
    for line in inputFile:
      if line.startswith('#'):
        if allowComments:
          bashrc.write(line)
      else:
        bashrc.write(unicode(line))
    handleBashrcFileWrite(bashrc, isPrivateFile)

def createSymlink(targetName, linkName)	:
  target = destDir + targetName
  link = homeDir + linkName
  print "Symlink " + link + " -> " + target
  if os.path.islink(link):
    print "\tLink exists. Checking..."
    try:
      os.stat(link)
    except OSError, e:
      if e.errno == 2:
        print "\tLink is broken. Removing..."
        os.remove(link)
      else:
        raise
    else:
      print "\tLink is valid."
      return
  else:
    print "\tSymlink does not exist. Creating..."
  os.symlink(target, link)
  print "\tLink created."

def install():
  print "Compiling sections..."
  with open('bash_common','r') as bashCommon:
      addInputFileContents(bashCommon,False,False)
  if os.path.isfile('bash_private'):
    with open('bash_private','r') as bashPrivate:
      addInputFileContents(bashPrivate,False,True)
  if sysName == 'Linux':
    with open('bash_linux','r') as bashLinux:
      addInputFileContents(bashLinux,True,False)
  elif sysName == 'Darwin':
    with open('bash_mac','r') as bashMac:
      addInputFileContents(bashMac,True,False)

  createSymlink(bashOutputDotFile, bashOutputDotFile)
  createSymlink('vimrc','.vimrc')

  print "Done."

def main():
  init()
  identifySystem()
  cleanUp()
  addBashOutputFileHeader()
  install()

if __name__ == '__main__':
  main()

@@ -156,90 +156,8 @@
  sys
-%0AsysName = ''%0AhomeDir = ''%0AdestDir = ''%0AbashOutputFile = ''%0AbashOutputDotFile = ''
 %0A%0Ade

Remove unneeded module-level var declarations.