# -*- coding: utf-8 -*-
import logging, mv_common
import os, re , glob
from time import time, localtime, strftime
import time
import pwd

def setup_lirc_links(mythhome):
    logging.debug("    Creating links for lirc")
    try:
        mythuid = pwd.getpwnam('mythtv')[2]
        mythgid = pwd.getpwnam('mythtv')[3]
    except:
        logging.critical("*    mythuid not found")
        mythuid = '1000'
        mythgid = '1000'
    if not os.path.exists(mythhome+"/.mythtv"):
        logging.debug("    Creating %s/.mythtv",mythhome)
        try:
            os.mkdir(mythhome+"/.mythtv")
        except:
            logging.debug("   Couldn't create .mythtv ")
            return
        try:
            os.chown(mythhome+"/.mythtv", mythuid, mythgid)
            logging.debug("*    Couldn't chown of %s", mythhome)
        except:
            cmd = ''' chown -R mythtv %s/.mythtv''' %mythhome
            mv_common.runcmd(cmd)
            cmd = ''' chgrp -R mythtv %s/.mythtv''' %mythhome
            mv_common.runcmd(cmd)
            pass

    if os.path.exists("/etc/lircrc"):
        if not os.path.exists(mythhome+"/.mythtv/lircrc"):
            logging.debug("    Creating symlink for myth lircrc")
            os.symlink("/etc/lircrc",mythhome+"/.mythtv/lircrc")
        else:
            logging.debug("    %s/lircrc already present",mythhome)

        if not os.path.exists(mythhome+"/.lircrc"):
            logging.debug("    Creating symlink for lircrc")
            os.symlink("/etc/lircrc",mythhome+"/.lircrc")
        else:
            logging.debug("    %s/.lircrc already present",mythhome)
    else:
        logging.debug("    /etc/lircrc does not exisit, can not link it")

def scrub_modules(filename,module):
    logging.debug("    scrubbing %s from %s",module,filename)
    cmd = '''sed -i -e '/.*#%s/d' %s''' %(module,filename)
    mv_common.runcmd(cmd)

def add_module(filename,module):
    logging.debug("    adding  %s to %s",module,filename)
    cmd = ''' echo "%s" >> %s ''' %(module,filename)
    mv_common.runcmd(cmd)

def unload_all_lirc():
    logging.debug("    Unloading all lirc modules")
    cmd = "sv stop lircd"
    mv_common.runcmd(cmd)
    cmd = "killall -9 lircd"
    mv_common.runcmd(cmd)
    cmd = '''modprobe -r $(lsmod |grep ^lirc |awk '{print $1}') '''
    mv_common.runcmd(cmd)



def include_file( incfile,filename):
    logging.debug("     including %s within %s",filename,incfile)
    try:
        f = open( incfile, 'a')
    except:
        logging.debug("    Couldn't open %s for writing",incfile)
        return
    line = '''include "%s" ''' %filename
    logging.debug("   %s",line)
    f.write(line)
    f.write("\n")
    f.close()

def setup_ir_remote(Remotetype,templates):
    logging.debug("    Setup of remote type %s",Remotetype)
    if Remotetype == "no_remote":
        mv_common.remove_service("lircd")
    elif Remotetype == "tinker":
        pass
    else:
        currenttime = strftime("%b-%d-%Y-%H:%M:%S", localtime())
        cmd = "mv /etc/lircd.conf /etc/lircd.conf-%s" %currenttime
        mv_common.runcmd(cmd)
        cmd = "mv /etc/lircrc /etc/lircrc-%s" %currenttime
        mv_common.runcmd(cmd)
        files = templates + "/remotes/" + Remotetype + "/lircd*"
        logging.debug("    Using %s",files)
        for filename in glob.glob(files):
            # Ignore subfolders
            if os.path.isdir (filename):
                logging.debug("    %s is a dir, skipping",filename)
                continue
            include_file("/etc/lircd.conf",filename)
        files = templates + "/remotes/" + Remotetype + "/lircrc*"
        logging.debug("    Using %s",files)
        for filename in glob.glob(files):
            # Ignore subfolders
            if os.path.isdir (filename):
                logging.debug("    %s is a dir, skipping",filename)
                continue
            include_file("/etc/lircrc",filename)
        cmd =  "chmod 755 /etc/lircrc"
        mv_common.runcmd(cmd)
        mv_common.add_service("lircd")


def setup_ir_receiver(ReceiverType,TEMPLATES):
    logging.info("    Configuring receiver %s", ReceiverType)
    if ReceiverType == "Serial":
        scrub_modules("/etc/modules.mythvantage","lirc")
        add_module("/etc/modules.mythvantage","lirc_serial    #lirc")
        cmd = "load-modules-mythvantage.sh"
        mv_common.runcmd(cmd)
        mv_common.remove_service("igdaemon")
        mv_common.remove_service("tatir")

    elif ReceiverType == "Usb-imon":
        scrub_modules("/etc/modules.mythvantage","lirc")
        add_module("/etc/modules.mythvantage","lirc_imon    #lirc")
        cmd = "load-modules-mythvantage.sh"
        mv_common.runcmd(cmd)
        mv_common.remove_service("igdaemon")
        mv_common.remove_service("tatir")

    elif ReceiverType == "Hauppauge":
        scrub_modules("/etc/modules.mythvantage","lirc")
        add_module("/etc/modules.mythvantage","lirc_i2c    #lirc")
        mv_common.cp_and_log(TEMPLATES+"/modules/lirc_i2c.conf" ,
                             "/etc/modprobe.d/lirc_i2c.conf")
        cmd = "rmmod lirc_i2c"
        mv_common.runcmd(cmd)
        cmd = "load-modules-mythvantage.sh"
        mv_common.runcmd(cmd)
        mv_common.remove_service("igdaemon")
        mv_common.remove_service("tatir")
    elif ReceiverType == "pvr150":
        scrub_modules("/etc/modules.mythvantage","lirc")
        add_module("/etc/modules.mythvantage","lirc_i2c    #lirc")
        mv_common.cp_and_log(TEMPLATES+"/modules/lirc_i2c.conf" ,
                             "/etc/modprobe.d/lirc_i2c.conf")
        cmd = "rmmod lirc_i2c"
        mv_common.runcmd(cmd)
        cmd = "load-modules-mythvantage.sh"
        mv_common.runcmd(cmd)
        mv_common.remove_service("igdaemon")
        mv_common.remove_service("tatir")
    elif ReceiverType == "iguanaIR-usb":
        scrub_modules("/etc/modules.mythvantage","lirc")
        mv_common.add_service("igdaemon")
        mv_common.remove_service("tatir")

    elif ReceiverType == "tatir":
        scrub_modules("/etc/modules.mythvantage","lirc")
        mv_common.add_service("tatir")
        mv_common.remove_service("igdaemon")

    else:
        logging.debug("    didn't match receiver, using genric case")
        scrub_modules("/etc/modules.mythvantage","lirc")
        mv_common.remove_service("igdaemon")
        mv_common.remove_service("tatir")

def setup_blaster_proto(HostBlasterType,Hostnumblaster,TEMPLATES,systemconfig):
    logging.debug("    Start of setup_blaster_proto")
    logging.debug("    HostBlasterType: %s", HostBlasterType)
    logging.debug("    Hostnumblaster: %s" , Hostnumblaster)
    if not HostBlasterType == "pvr150" and not HostBlasterType == "None":
        for i in range(int(Hostnumblaster)):
            try:
                proto = systemconfig["HostTransmitproto_"+str(i+1)]
                logging.debug("    proto: %s",proto)
            except:
               logging.info("    unkown proto for %s",i+1)
               continue
            template=TEMPLATES+"/transmit/%s/lircd.conf" %proto
            if os.path.exists(template):
                logging.debug("    include blaster template: %s",proto)
                include_file("/etc/lircd.conf",template)
            else:
                logging.debug("    template: %s is not present",template)
    logging.info("------NEED TO SETUP CHANGE_CHANNEL------")


def setup_blaster_transmiter(HostBlasterType):
    logging.debug("    Start of setup_blaster_transmiter")
    logging.info("    HostBlasterType : %s", HostBlasterType)

    if  HostBlasterType == "Receiver":
        logging.info("    Blaster is receiver, skipping module config for Blaster")
        return

    if HostBlasterType == "no blaster":
        scrub_modules("/etc/modules.mythvantage","blaster")
    elif HostBlasterType == "Serial":
        scrub_modules("/etc/modules.mythvantage","blaster")
        add_module("/etc/modules/.mythvantage","lirc_serial    #blaster")
        cmd = "load-modules-mythvantage.sh"
        mv_common.runcmd(cmd)
    elif HostBlasterType == "pvr150":
        scrub_modules("/etc/modules.mythvantage", "blaster")
        scrub_modules("/etc/modules.mythvantage", "lirc")
        add_module("/etc/modules.mythvantage", "lirc_pvr150    #blaster")
        add_module("/etc/modules.mythvantage", "lirc_pvr150    #lirc")
        cmd = "rmmod lirc_i2c"
        mv_common.runcmd(cmd)
        cmd = "load-modules-mythvantage.sh"
        mv_common.runcmd(cmd)
    else:
        scrub_modules("/etc/modules.mythvantage","blaster")

def setup_lcd(LCDtype, TEMPLATES, Remotetype):
    logging.debug("____Start of setup_lcd____")
    logging.debug("    LCDType: %s", LCDtype)
    logging.debug("    Remotetype: %s", Remotetype)
    if LCDtype == "tinker":
        logging.info("   tinker mode detected")
        return

    if LCDtype == "no_lcd":
        logging.info("    Disabling LCD support")
        cmd = "sv stop lcdd"
        mv_common.runcmd(cmd)
        #sometimes it doesn't want to die
        cmd = "killall -9 LCDd"
        mv_common.runcmd(cmd)
        cmd = "load-modules-mythvantage.sh  UNLOAD LCD"
        mv_common.runcmd(cmd)
        scrub_modules("/etc/modules.mythvantage", "LCD")
        mv_common.remove_service("lcdd")
    else:
        lcdmodule="%s/LCD/%s/modules" %(TEMPLATES,LCDtype)
        if os.path.exists(lcdmodule):
            logging.debug("    Adding module for LCD")
            scrub_modules("/etc/modules.mythvantage", "LCD")
            cmd = "cat %s >> /etc/modules.mythvantage" %lcdmodule
            mv_common.runcmd(cmd)
        if Remotetype != "tinker":
            lcdconf = "%s/LCD/%s/LCDd.conf" %(TEMPLATES,LCDtype)
            lcdlirc = "%s/LCD/%s" %(TEMPLATES,LCDtype)
            mv_common.pacinstall("lcdproc")
            if os.path.exists(lcdconf):
                logging.debug("    Copying in lcdconf template file: %s",lcdconf)
                mv_common.cp_and_log(lcdconf, "/etc/LCDd.conf")
            else:
                logging.debug("    %s is not present, will not copy it")

            if os.path.exists(lcdlirc+"/lircrc"):
                logging.debug("    LCD seems to support lirc")
                #setup the lirc aspect of the lcd
                #copied from setup_ir_remote
                files = lcdlirc+"/lircd*"
                logging.debug("    Using %s",files)
                for filename in glob.glob(files):
                    # Ignore subfolders
                    if os.path.isdir (filename):
                        logging.debug("    %s is a dir, skipping",filename)
                        continue
                    include_file("/etc/lircd.conf",filename)
                files = lcdlirc+"/lircrc*"
                logging.debug("    Using %s",files)
                for filename in glob.glob(files):
                    # Ignore subfolders
                    if os.path.isdir (filename):
                        logging.debug("    %s is a dir, skipping",filename)
                        continue
                    include_file("/etc/lircrc",filename)
                cmd =  "chmod 755 /etc/lircrc"
                mv_common.runcmd(cmd)

            mv_common.add_service("lcdd")
            mv_common.restart_service("lcdd")
    logging.debug("__End of setup_lcd")

def setup_ir(systemconfig, data_config):
    rc = False
    logging.info("____Start of IR____")
    if systemconfig["Remotetype"] == "tinker":
        logging.info("    Tinker mode detected")
    else:
        if not systemconfig["HostBlasterType"]:
            HostBlasterType = "unknown"
            Hostnumblaster = "0"
        else:
            HostBlasterType = systemconfig["HostBlasterType"]
            Hostnumblaster  = systemconfig["Hostnumblaster"]

        if systemconfig["HostBlasterType"] == "pvr150":
            remotetype = "hauppauge-blaster"
            logging.debug("    pvr150 blaster selected, setting remote to hauppauge-blaster")
        else:
            remotetype = systemconfig["Remotetype"]

        setup_ir_remote(remotetype,systemconfig["TEMPLATES"])
        setup_lirc_links(data_config.MYTHHOME)

        if systemconfig["ReceiverType"]:
            setup_ir_receiver(systemconfig["ReceiverType"],
                              systemconfig["TEMPLATES"])
        else:
            setup_ir_receiver("unknown", systemconfig["TEMPLATES"])
        unload_all_lirc()
        setup_blaster_proto(HostBlasterType,
                            Hostnumblaster,
                            systemconfig["TEMPLATES"],
                            systemconfig)
        setup_blaster_transmiter(HostBlasterType)
        cmd = "load-modules-mythvantage.sh"
        mv_common.runcmd(cmd)
        time.sleep(2)
        mv_common.udev_trigger()
        cmd="sv start lircd"
        mv_common.runcmd(cmd)
        rc = [ True , True ]
    if systemconfig["LCDtype"]:
        setup_lcd(systemconfig["LCDtype"],
                  systemconfig["TEMPLATES"],
                  systemconfig["Remotetype"])
    else:
        logging.debug("    LCD not defined")
    logging.info("__End IR\n")
    return rc