#!/usr/bin/env python3
# vim: set ts=4 sw=4 sts=4 et smarttab smartindent sta
import sys
import os
import glob

SELF = __file__
DIRNAME = os.path.dirname(SELF)
DIRNAME = os.path.abspath(DIRNAME)
HOME = os.getenv('HOME')


def mkdirs(path):
    if os.access(path, os.X_OK):
        return
    os.makedirs(path)


def func(src, removeOnly=False):
    FILENAME = src[len(DIRNAME) + 1:]
    DEST = os.path.join(HOME, FILENAME)
    try:
        if os.path.islink(DEST):
            os.unlink(DEST)
        elif os.path.isfile(DEST):
            os.unlink(DEST)
        elif os.path.isdir(DEST):
            print('DEST file "%s" is directory. abort.' % DEST)
            return False
        elif not os.path.exists(DEST):
            pass
        else:
            assert False, DEST
        if not removeOnly:
            os.symlink(src, DEST)
    except OSError:
        return False
    return True


if __name__ == '__main__':
    UNINSTALL = '-u' in sys.argv
    # install hidden files
    files = glob.glob(os.path.join(DIRNAME, ".*"))
    files += glob.glob(os.path.join(DIRNAME, "*"))

    if not UNINSTALL:
        cmd = '$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)'
        # check ohmyzsh installation
        if not os.access(os.path.join(os.environ['HOME'], '.oh-my-zsh'), os.F_OK):
            os.system('bash -c "%s"' % cmd)
        os.system('git submodule init && git submodule sync')
        VIM_INSTALL = os.path.join(DIRNAME, 'bin', 'vim-install')
        os.system('bash -c %s' % VIM_INSTALL)
        FONT_CONF_D = os.path.join(HOME, '.config', 'fontconfig', 'conf.d')
        FONTS_DIR = os.path.join(HOME, '.fonts')
        POWERLINE_FONT_DIR = os.path.join(
            HOME, '.vim', 'bundle', 'powerline', 'font')

    # ignore list
    for F in ('install', 'README', '.git', '.gitmodules', 'aosp', '.vim'):
        files.remove(os.path.join(DIRNAME, F))

    for I in files:
        if not func(I, UNINSTALL):
            pass
