# -*- 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")
            mv_common.link_file("/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")
            mv_common.link_file("/etc/lircrc",mythhome+"/.lircrc")
        else:
            logging.debug("    %s/.lircrc already present",mythhome)
    else:
        logging.debug("    /etc/lircrc does not exist, can not link it")

    if os.path.exists("/etc/wol-lircrc"):
        if not os.path.exists(mythhome+"/.wol-lircrc"):
            logging.debug("    Creating symlink for .wol-lircrc")
            #os.symlink("/etc/wol-lircrc",mythhome+"/.wol-lircrc")
            mv_common.link_file("/etc/wol-lircrc",mythhome+"/.wol-lircrc")
        else:
            logging.debug("    %s/.wol-lircrc already present",mythhome)
    else:
        logging.debug("    /etc/wol-lircrc does not exist, 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(Remotetype, this_is_install):
    if this_is_install == False:
        logging.debug("    Unloading all remote modules")
        #ati bucket specific
        if "snapstream_firefly" in Remotetype :
            cmd = "rmmod ati_remote"
            mv_common.runcmd(cmd)
        cmd = "sv stop remotes"
        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,mythhome,HostBlasterType,remotebucket):
    logging.debug("    Setup of remote type %s",Remotetype)
    #if Remotetype == "no_remote" and HostBlasterType == "None" :
    HostBlasterType_values=["None",""]
    if Remotetype == "no_remote" and (HostBlasterType in HostBlasterType_values)  :
        mv_common.remove_service("remotes")
        mv_common.remove_service("irexec")
    elif Remotetype == "tinker":
        pass #do nothing
    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/lirc/lircd.conf.d/remote_lircd.conf /etc/lirc/lircd.conf.d/remote_lircd.conf-%s" %currenttime
        mv_common.runcmd(cmd)
        cmd = "mv /etc/lirc/lircd.conf.d/blaster_lircd.conf /etc/lirc/lircd.conf.d/blaster_lircd.conf-%s" %currenttime
        mv_common.runcmd(cmd)
        cmd = "mv /etc/lirc/lircd.conf.d/lcd_lircd.conf /etc/lirc/lircd.conf.d/lcd_lircd.conf-%s" %currenttime
        mv_common.runcmd(cmd)
        cmd = "mv /etc/lircrc /etc/lircrc-%s" %currenttime
        mv_common.runcmd(cmd)
        cmd = "mv /etc/wol-lircrc /etc/wol-lircrc-%s" %currenttime
        mv_common.runcmd(cmd)
        cmd = "mv /etc/remote.run /etc/remote.run-%s" %currenttime
        mv_common.runcmd(cmd)
        if remotebucket == "user":
            remote_path = "%s/remotes/%s"  %(mythhome,Remotetype)
        else:
            remote_path="%s/remotes/%s/%s" %(templates,remotebucket,Remotetype)

        files =  remote_path + "/lircd*"
        logging.debug("    Using %s",files)
        # was /etc/lircd.conf symlink
        # /etc/lirc/lircd.conf.d/remote_lircd.conf symlink
        for filename in glob.glob(files):
            # Ignore subfolders
            if os.path.isdir (filename):
                logging.debug("    %s is a dir, skipping",filename)
                continue
            mv_common.link_file(filename,"/etc/lirc/lircd.conf.d/remote_lircd.conf")
        #files = templates + "/remotes/" + Remotetype + "/lircrc*"

        # include lircrc
        files = remote_path + "/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)

        # include wol-lircrc
        files = remote_path + "/wol-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/wol-lircrc",filename)

        #if remote has a special run file use it.
        files = remote_path + "/remote.run*"
        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
            cmd = "cp %s /etc/remote.run" %filename
            mv_common.runcmd(cmd)

        #if remote has a Lircmap.xml file, use it for kodi and plexht.
        kodifile= remote_path + "/Lircmap.xml"

        for app in ['Kodi', 'PlexHT']:
            if app == 'Kodi':
                userLircmap = mythhome+"/.kodi/userdata/Lircmap.xml"
                userdirname = ".kodi"
            elif app == 'PlexHT':
                userLircmap = mythhome+"/.plexht/userdata/Lircmap.xml"
                userdirname = ".plexht"

            if os.path.exists(kodifile):
                logging.debug("    %s lirc file present at %s", app, kodifile)
                logging.info("    Setting up lirc for %s",app)
                if not os.path.exists(mythhome+"/"+userdirname+"/userdata"):
                    logging.debug("    Creating %s/%s", mythhome, userdirname)
                    try:
                        os.mkdir(mythhome+"/"+userdirname)
                    except:
                        logging.debug("   Couldn't create %s/ ",userdirname)
                    try:
                        os.mkdir(mythhome+"/"+userdirname+"/userdata/")
                    except:
                        logging.debug("   Couldn't create %s/userdata",userdirname)

                    try:
                        cmd = ''' chown -R mythtv %s/%s''' %(mythhome,userdirname)
                        mv_common.runcmd(cmd)
                        cmd = ''' chgrp -R mythtv %s/%s/userdata''' %(mythhome,userdirname)
                        mv_common.runcmd(cmd)
                    except:
                        logging.debug("   Couldn't change permissions for %s",userdirname)
                        pass
                try:
                        cmd = ''' rm -f %s''' %(userLircmap)
                        mv_common.runcmd(cmd)
                        logging.debug("    Creating symlink for %s Lircmap.xml",app)
                        mv_common.link_file(kodifile, mythhome+"/"+userdirname+"/userdata/Lircmap.xml")
                except:
                    pass
            else:
                logging.debug("    %s Lircmap file %s not present", userdirname, kodifile)
                logging.debug("    Checking if %s is a symlink", userLircmap)
                if os.path.islink(userLircmap):
                    logging.info("    Removing symlink %s", userLircmap)
                    cmd = ''' rm -f %s''' %(userLircmap)
                    mv_common.runcmd(cmd)
                else:
                    logging.debug("    Not a symlink %s", userLircmap)


        #remote has it's own modprobe.d/conf filename
        cmd = "rm  -f /etc/modprobe.d/mv_ir.conf"
        mv_common.runcmd(cmd)
        files = remote_path + "/ir.conf*"
        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
            cmd = "cp %s /etc/modprobe.d/mv_ir.conf" %filename
            mv_common.runcmd(cmd)


        #cleanup
        cmd =  "chmod 755 /etc/lircrc /etc/wol-lircrc /etc/remote.run"
        mv_common.runcmd(cmd)
        mv_common.add_service("remotes")
        mv_common.add_service("irexec")


def setup_ir_receiver(ReceiverType,TEMPLATES,HDHRlirc_device,myip):
    logging.info("    Configuring receiver %s", ReceiverType)
    if ReceiverType == "serial":
        scrub_modules("/etc/modules.mythvantage","lirc")
        #loading takes place in remotes/run
        #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")
    elif ReceiverType == "SiliconDust_HDHR":
        mv_common.remove_service("igdaemon")
        mv_common.remove_service("tatir")
        cmd = '''hdhomerun_config %s set /ir/target "%s:5000 no_clear"''' %(HDHRlirc_device,myip)
        print cmd
        mv_common.runcmd(cmd)
        cmd = '''hdhomerun_config %s set /ir/target "%s:5000 store"''' %(HDHRlirc_device,myip)
        print cmd
        mv_common.runcmd(cmd)


    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("    link blaster template: %s",proto)
                mv_common.link_file(template,"/etc/lirc/lircd.conf.d/blaster_lircd.conf")
                #include_file("/etc/lircd.conf",template)
            else:
                logging.debug("    template: %s is not present",template)



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 == "iguanaIR-usb":
        mv_common.add_service("igdaemon")
    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, this_is_install):
    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
        if this_is_install == False:
            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
                    mv_common.link_file(filename,"/etc/lirc/lircd.conf.d/lcd_lircd.conf")
                    #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, this_is_install):
    rc = [ False , False ]
    if  mv_common.read_config(mv_common.module_config,"ir")  == False  :
        logging.info("____Skipping of IR, config disabled____")
        return rc

    logging.info("____Start of IR____")
    if systemconfig.get("Remotetype") == "tinker":
        logging.info("    Tinker mode detected")
    else:
        if not systemconfig.get("HostBlasterType"):
            HostBlasterType = "unknown"
            Hostnumblaster = "0"
        else:
            HostBlasterType = systemconfig.get("HostBlasterType")
            Hostnumblaster  = systemconfig.get("Hostnumblaster")

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

        setup_ir_remote(remotetype,systemconfig.get("TEMPLATES"),
                            data_config.MYTHHOME,
                            systemconfig.get("HostBlasterType"),
                            systemconfig.get("Remotebucket"))
        setup_lirc_links(data_config.MYTHHOME)

        if systemconfig.get("ReceiverType"):
            setup_ir_receiver(systemconfig.get("ReceiverType"),
                              systemconfig.get("TEMPLATES"),
                              systemconfig.get("HDHRlirc_device"),
                              systemconfig.get("mythip"))
        else:
            setup_ir_receiver("unknown", systemconfig.get("TEMPLATES"),'','127.0.0.1')
        unload_all_lirc(remotetype, this_is_install)
        setup_blaster_proto(HostBlasterType,
                            Hostnumblaster,
                            systemconfig.get("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 remotes"
        mv_common.runcmd(cmd)
        rc = [ True , True ]
    if systemconfig.get("LCDtype"):
        setup_lcd(systemconfig.get("LCDtype"),
                  systemconfig.get("TEMPLATES"),
                  systemconfig.get("Remotetype"),
                  this_is_install)
    else:
        logging.debug("    LCD not defined")
    logging.info("__End IR\n")
    return rc
