#!/usr/bin/env python2
"""
A simple script to create a symlinks in your home directory for every filename
in this directory.

For example:
    ~/.bashrc -> dot-files/bashrc
"""

from os import getcwd, listdir, getenv, symlink, remove
from os.path import (dirname, basename, join, expanduser, lexists, exists,
                     relpath, normpath, isfile, islink, realpath, abspath)

def log(filename, message):
    """Simple logging function"""
    name = "'{0}':".format(filename).ljust(30, ' ')
    print "{0}\t{0}".format(name, message)

def dir_filter(file_name):
    return file_name != basename(__file__) and \
           file_name != 'README.md' and \
           file_name[0] != '.'

def main():
    """Create the symlinks"""
    dir_path = dirname(__file__)
    base_name = dirname(normpath(join(getenv('PWD'), __file__)))
    home_dir = expanduser('~')
    rel_path = normpath(relpath(base_name, home_dir))

    for filename in filter(dir_filter, listdir(dirname(abspath(__file__)))):
        config_path = join(home_dir, ".{0}".format(filename))
        file_path = join(rel_path, filename)

        # If the current file is going to be linked deeper in the
        # home directory, for example, we want to link
        # `~/.ssh/config` instead of the whole `~/.ssh` directory.
        if filename[0] == '_':
            deep_dirs = filename[1:].split('_')
            link_file = deep_dirs[-1]
            dir_name = join(*deep_dirs[:-1])
            config_path = join(home_dir, ".{0}".format(dir_name), link_file)
            file_path = join("..", file_path)

        if lexists(config_path):
            if not exists(config_path):
                # If it does not exists but lexists is true, that means this
                # is a broken symlink
                remove(config_path)
            elif islink(config_path):
                if realpath(config_path) != file_path:
                    continue
            elif isfile(config_path):
                log(config_path, 'existing file, consider merge')
                continue

        log(config_path, "now linking to '{0}'".format(file_path))
        symlink(file_path, config_path)

if __name__ == '__main__':
    main()