#!/usr/bin/env python2

import errno
import os
import sys

if os.path.dirname(__file__) != '.':
	print 'This script must be run from the dotfiles directory.'
	sys.exit(1)
script = os.path.basename(__file__)

def link_file(target, name):
	try:
		os.symlink(target, name)
		print '\033[36;1m' + name + '\033[0m ->', target
	except OSError as e:
		if e.errno != errno.EEXIST:
			raise
		try:
			if os.readlink(name) == target:
				print name, 'is already linked'
			else:
				print name, '\033[31;1mexists\033[0m (symlink)'
		except OSError as e:
			if e.errno == errno.EINVAL:
				print name, '\033[31;1mexists\033[0m'
			else:
				raise

for f in os.listdir('.'):
	if f in [script, '.git', '.gitignore']:
		continue

	name = '../.' + f
	target = 'dotfiles/' + f
	# ~/.vim is a special case since we symlink the whole directory
	# everywhere else, we create the directory and symlink the contents
	if f == 'vim' or not os.path.isdir(f):
		link_file(target, name)
	else:
		for dirpath, _, filenames in os.walk(f):
			try:
				dirname = '../.' + dirpath
				os.mkdir(dirname)
				print 'Created \033[34;1m' + dirname + '\033[0m'
			except OSError as e:
				if e.errno == errno.EEXIST:
					print 'No need to create', dirname
				else:
					raise
			prefix = '../' * (dirpath.count('/') + 1)
			for f in filenames:
				link_file(prefix + 'dotfiles/' + dirpath + '/' + f, '../.' + dirpath + '/' + f)

# config/nvim is skipped because we ignore dirs from os.walk
link_file('../dotfiles/vim', '../.config/nvim')

vim_swap = '../.vim_swap'
if os.path.exists(vim_swap):
	print 'No need to create', vim_swap
else:
	os.mkdir(vim_swap, 0700)
	print 'Created \033[34;1m' + vim_swap + '\033[0m'
