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

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

import os

def log(filename, message):
    """Simple logging function"""
    name = ("'%s':" % filename).ljust(30, ' ')
    print "%s\t%s" % (name, message)

def main():
    """Create the symlinks"""
    abs_path = os.path.abspath(os.path.dirname(__file__))
    home_dir = os.path.expanduser('~')
    this_script = os.path.basename(__file__)
    rel_path = abs_path.replace(home_dir, '.')

    for filename in os.listdir(abs_path):
        if filename == this_script:
            continue
        if filename == 'README.md':
            continue

        config_path = os.path.join(home_dir, ".%s" % filename)
        file_path = os.path.join(rel_path, filename)

        # If the current file is a hidden file, ignore it
        if filename[0] == '.':
            continue

        # 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 = os.path.join(home_dir, ".%s" % dir_name, link_file)
            file_path = "../%s" % file_path

        if os.path.exists(config_path):
            if os.path.islink(config_path):
                if os.path.realpath(config_path) != file_path:
                    pass
            elif os.path.isfile(config_path):
                log(config_path, 'existing file, consider merge')
            continue

        os.symlink(file_path, config_path)
        log(config_path, "now linking to '%s'" % file_path)

    return

if __name__ == '__main__':
    main()