#!/usr/bin/python3

import errno
import os.path
import logging
from optparse import OptionParser
import shutil
import sys

from gi.repository import Click


def rename(old, new):
    logging.debug("rename %s -> %s" % (old, new))
    try:
        os.rename(old, new)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

def rmtree(path):
    logging.debug("rmtree %s (%s)" % (path, os.listdir(path)))
    shutil.rmtree(path, ignore_errors=True)


if __name__  == "__main__":
    parser = OptionParser()
    parser.add_option("-v", "--verbose", default=False, action="store_true",
                      help="verbose output")
    parser.add_option("", "--srcdir", default="~/.cache/click-bin-path/",
                      help="Source directory to use")
    parser.add_option("", "--dstdir", default="~/click-bin/",
                      help="Target directory to use")
    (options, args) = parser.parse_args()

    srcdir = os.path.expanduser(options.srcdir)
    dstdir = os.path.expanduser(options.dstdir)
    Click.ensuredir(dstdir)

    if options.verbose or os.environ.get("CLICK_BIN_PATH_DEBUG", ""):
        logging.basicConfig(level=logging.DEBUG)
        logging.info("Enable debugging")

    # if there is no srcdir (yet) there is nothing to do for us
    if not os.path.exists(srcdir):
        logging.debug("no srcdir, exiting")
        sys.exit(0)

    success = True
    src = set([os.path.realpath(os.path.join(srcdir, f))
               for f in os.listdir(srcdir)])
    dst = set([os.path.realpath(os.path.join(dstdir, f))
               for f in os.listdir(dstdir)])
    logging.debug("src: %s" % src)
    logging.debug("dst: %s" % dst)

    for removed in dst - src:
        os.unlink(os.path.join(dstdir, os.path.basename(removed)))

    for new in src - dst:
        dest =  os.path.join(dstdir, os.path.basename(new))
        if os.path.exists(dest):
            logging.warning("%s already exists, ignoring %s" % (dest, new))
            success = False
            continue
        os.symlink(new, dest)

    if not success:
        sys.exit(1)

