#!/usr/bin/python
import os
import re
import logging

from l3tlib import Error
from l3tlib.command import L3tBugCommand


log = logging.getLogger("l3t-make-sr-links")


class MakeSRLinks(L3tBugCommand):

    descr = "Creates symlinks for the ziu:SR* referred in the bug"

    def init_parser(self, parser):
        super(MakeSRLinks, self).init_parser(parser)
        parser.add_option("-d", "--dest", default=".",
                          help="Target directory (defaults to .)")
        parser.add_option("--force", default=False, action="store_true",
                          help="Overwrite existing symlinks")

    def find_refs(self, bug):
        expr_sr = re.compile(self.config.ziu.reference_regexp)
        for comment in bug.comments:
            for found in expr_sr.finditer(comment.get("thetext", "")):
                if found:
                    base = found.group("base")
                    yield base

    def create_link(self, source, dest):
        create = True
        if os.path.exists(dest):
            if self.opts.force:
                log.debug("removing %s" % (dest))
                try:
                    os.unlink(dest)
                except EnvironmentError, e:
                    raise Error("failed to unlink existing file: %s" % (e))
            else:
                print "skipping", dest
                create = False
        if create:
            print source, "->", dest
            try:
                os.symlink(source, dest)
            except EnvironmentError, e:
                raise Error("failed to symlink %s to %s: %s" % (source,
                                                                dest, e))

    def run(self):
        bug = self.l3t.get_bug(self.opts.incident, self.opts.bug)
        for dirname in self.find_refs(bug):
            path = os.path.join(self.config.ziu.mount, dirname)
            if os.path.exists(path):
                dest = os.path.join(self.opts.dest, dirname)
                self.create_link(path, dest)
            else:
                msg = ("%s not found in %s (is it mounted?)" %
                       (dirname, self.config.ziu.mount))
                print msg


MakeSRLinks().main()
