# -*- coding: utf-8 -*-
import logging, os, re
import mv_common
import glob

def setup_pacman(create_link):
    if create_link:
        logging.info("    Creating pacman link")
        #LOOK
        #This is not implmented yet, below is the bash code for reference
        #if [ ! x$1 = x ]
    #then
        #ln -s ${BASE}/data/var ${BASE}/data/srv/httpd/htdocs/repo
        #echo "creating the link for the pacman repo mirror"
    #fi

    #for i in mv-core mv-core-testing mv-extra mv-extra-testing
    #do
        #echo "[$i]"  > ${BASE}/etc/pacman.d/$i
        ##add mirror if needed
        #if [ x$PKG_MIRROR = x1 ]
        #then
            #echo " Server = http://$dbhost/repo/$i " >> ${BASE}/etc/pacman.d/$i
        #fi
        ##add user templates
        #USERTEMPLATES="/data/home/mythtv/templates"
        #if [ -f $USERTEMPLATES/sources/$i ]
        #then
            #echo "Adding user  $i"
            #cat $USERTEMPLATES/sources/$i  >> ${BASE}/etc/pacman.d/$i
        #fi
        #cat $TEMPLATES/sources/$i  >> ${BASE}/etc/pacman.d/$i
        #echo "setting local mirror to $dbhost for $i "
    #done
    else:
        logging.info("    Pacman link will not be created")
    return
def setup_ncid_client(runclient,runserver):
    logging.debug("    Configuring ncid client")
    if runclient == "1" :
        mv_common.pacinstall("ncid")
        mv_common.add_service("ncid-client")
    else:
        logging.debug("    Removing ncid client")
        mv_common.remove_service("ncid-client")
    return

def setup_ncid_daemon(Runncidd):
    logging.info("    Configuring callerid daemon")
    if Runncidd == "1":
        mv_common.pacinstall("ncid")
        mv_common.add_service("ncid-server")
        mv_common.add_service("ncid-logger")
    else:
        logging.debug("    Callerid will not run")
        mv_common.pacremove("ncid")
        mv_common.remove_service("ncid-server")
        mv_common.remove_service("ncid-logger")

    return



#def setup_ncid_client(dbhost,templatefile):
    ##This always runs
    #logging.debug("    Configuring ncid client with server %s",dbhost)
    #cmd = '''sed -e "s/^set Host.*$/set Host %s /" %s >/etc/ncid/ncid.conf''' %(dbhost, templatefile)
    #return

#def setup_ncid_daemon(port,templatefile,Runncidd):
    #logging.info("    Configuring callerid daemon")
    #if Runncidd == "1":
        #logging.debug("    Port: %s",port)
        #mv_common.cp_and_log("/etc/ncid/ncidd.conf",templatefile)
        #cmd = '''sed -e "s/.*set ttyport.*$/set ttyport =  \/dev\/%s /" %s >/etc/ncid/ncidd.conf''' %(port,templatefile)
        #mv_common.runcmd(cmd)
        #mv_common.pacinstall("ncidd")
        #mv_common.add_service("ncidd")
    #else:
        #logging.debug("    Callerid will not run")
        #mv_common.pacremove("ncidd")
        #mv_common.remove_service("ncidd")
    #return

def setup_splash(Usebootsplash):
    if Usebootsplash == "1":
        logging.info("    Enabling splash")
        cmd = ''' sed -i "s/^set default.*$/set default="0"/g" /boot/grub/grub.cfg'''
        mv_common.runcmd(cmd)
        #this is needed in case grub-mkconfig is run
        cmd = ''' sed -i "s/^GRUB_DEFAULT.*$/GRUB_DEFAULT="0"/g" /etc/default/grub'''
        mv_common.runcmd(cmd)
    else:
        logging.info("    Disabling splash")
        cmd = ''' sed -i "s/^set default.*$/set default="1"/g" /boot/grub/grub.cfg'''
        mv_common.runcmd(cmd)
        #this is needed in case grub-mkconfig is run
        cmd = ''' sed -i "s/^GRUB_DEFAULT.*$/GRUB_DEFAULT="1"/g" /etc/default/grub'''
        mv_common.runcmd(cmd)
    logging.info("    Running grub-mkconfig")
    cmd="grub-mkconfig -o /boot/grub/grub.cfg"
    mv_common.runcmd(cmd)
    return

#def setup_rrd(UseRRD):
    #if UseRRD == "1":
        #logging.info("    Enabling rrd_stats")
        #mv_common.pacinstall("rrd_stats")
    #else:
        #logging.info("    Disabling rrd_stats")
        #mv_common.pacremove("rrd_stats")


def setup_hobbit(UseHobbit,SystemType,dbhost):
    if UseHobbit == "1":
        if SystemType == "Standalone" or SystemType == "Master_backend":
            logging.info("    Installing hobbit server")
            mv_common.pacinstall("hobbitserver")
            mv_common.add_service("hobbit")
        else:
            logging.info("    Installing hobbit client")
            mv_common.pacinstall("hobbit-client")
            setup_hobbit_client(dbhost)
            mv_common.add_service("hobbit-client")

    else:
            logging.info("    Removing Hobbit")
            mv_common.pacremove("hobbit")
            mv_common.pacremove("hobbit-client")
            mv_common.remove_service("hobbit-client")
            mv_common.remove_service("hobbitserver")
            cmd = "rm -f /data/srv/httpd/htdocs/hobbit/index.html"
            mv_common.runcmd(cmd)
    return

def setup_hobbit_client(dbhost):
    logging.info("    Configuring hobbit client")
    logging.debug("   hobbit server is %s:", dbhost)
    cmd='''sed -i "s/^BBDISP.*$/BBDISP=%s/g" /data/srv/hobbit/client/etc/hobbitclient.cfg ''' %dbhost
    mv_common.runcmd(cmd)
    return

def setup_evrouter(UseEvrouter,EvrouterConfig,template):
    if UseEvrouter == "1":
        logging.info("    Configuring everouter")
        logging.debug("    EvrouterConfig is %s:",EvrouterConfig)
        if EvrouterConfig == "tinker":
            logging.debug("    tinker mode, not changing the config")
            return
        mv_common.pacinstall("evrouter")
        mv_common.pacinstall("Xvfb")
        mv_common.cp_and_log(template+"/evrouter/"+EvrouterConfig,"/etc/evrouter.cfg")
        mv_common.add_service("evrouter")
        mv_common.add_service("Xvfb")
    else:
        logging.info("    Not using evrouter")
        mv_common.pacremove("evrouter")
        mv_common.remove_service("evrouter")
        mv_common.remove_service("Xvfb")

    return

def setup_DNSmasq(RunDHCP,ip,gw,nameserver):
    if RunDHCP == "1":
        logging.info("    Configuring dhcp server(dnsmasq)")
        logging.debug("    ip: %s", ip)
        logging.debug("    gw: %s", gw)
        logging.debug("    ns: %s", nameserver)
        mv_common.pacinstall("dnsmasq")
        mv_common.pacinstall("mvpmc")
        mv_common.add_service("dnsmasq")
        logging.debug("    Setting default route to my gw: %s",gw)
        try:
            f = open("/etc/dnsmasq.conf",'r')
            dnsconf = f.readlines()
            f.close()
        except:
                logging.info("    Couldn't open dnsmasq.conf")
                return
        for line in dnsconf:
            outline = line
            if re.match("^dhcp-option=3",line):
                logging.debug("    Setting default route to my gw: %s",gw)
                outline = "dhcp-option=3,%s\n" %gw
            if re.match("^dhcp-option=6",line):
                logging.debug("    Setting dns to my ip: %s",ip)
                outline = "dhcp-option=6,%s\n" %ip
            f.write(outline)
        f.close()

        logging.debug("    change nfsroot to my ip:%s",ip)
        cmd = '''sed -i "s/nfsroot=.*:/nfsroot=%s:/g" /data/srv/tftp/pxelinux.cfg/default''' %ip
        mv_common.runcmd(cmd)

        logging.debug("    Adding 127.0.0.1 to resolv.conf")
        logging.debug("    other nameserver is %s",nameserver)
        try:
            f = open("/etc/resolv.conf",'r')
            dns = f.readlines()
            f.close()
        except:
                dns=''
                logging.debug("   Couldn't open resolv.conf for reading")
        try:
            f = open("/etc/resolv.conf",'w')
            line="search lan\n"
            f.write(line)
            line="nameserver 127.0.0.1\n"
            f.write(line)
            line="nameserver %s\n" %nameserver
            f.write(line)
            for line in dns:
                f.write(line)
            f.close()
        except:
                logging.debug("   Couldn't open resolv.conf for writing")

        logging.debug("    setup dongle.config")
        cmd = ''' sed -i "s/mvpmc -f .*/mvpmc -f \/etc\/helvR10.fon -s %s \& /" /data/srv/tftp/dongle.bin.config ''' %ip
        #COMMAND="%s/mvpmc -f .*/mvpmc -f \/etc\/helvR10.fon -s ${ip} \& /"
        #ex ${BASE}/data/srv/tftp/dongle.bin.config <<EOF
        mv_common.runcmd(cmd)
    else:
        logging.info("    removing dhcp server(dnsmasq)")
        mv_common.pacremove("dnsmasq")
        mv_common.pacremove("mvpmc")
        mv_common.remove_service("dnsmasq")
    return

def setup_mythweb(UseMythWEB):
    if UseMythWEB == "1":
        logging.info("    Activating mythweb")
        mv_common.pacinstall("lighttpd")
        mv_common.pacinstall("php-cgi")
        mv_common.pacinstall("mythweb")
        mv_common.add_service("lighttpd")
    else:
        logging.info("    Removing mythweb")
#        mv_common.pacremove("lighttpd")
        mv_common.pacremove("mythweb")
#       mv_common.remove_service("lighttpd")
    return

def setup_dyndns(DDnsEnable):
    if DDnsEnable == "1":
        logging.info("    Installing Dynamic DNS client")
        mv_common.pacinstall("inadyn")
        mv_common.add_service("inadyn")
    else:
        logging.info("    Removing Dynamic DNS client")
        mv_common.pacremove("inadyn")
        mv_common.remove_service("inadyn")


def setup_advanced(systemconfig,data_config):
    if  mv_common.read_config(mv_common.module_config,"advanced")  == False  :
        logging.info("____Skipping of Advanced, config disabled____")
        return
    logging.info("____Start of advanced configuration____")
    create_link = False
    if systemconfig.get("SystemType") == "Master_backend":
        create_link = True
    setup_pacman(create_link)



    if (( systemconfig.get("SystemType") == "Standalone" ) or (systemconfig.get("SystemType") == "Master_backend" )) :
        setup_ncid_daemon(systemconfig.get("Runncidd"))

    setup_ncid_client(systemconfig.get("ncidclient"),systemconfig.get("Runncidd"))


    setup_splash(systemconfig.get("Usebootsplash"))
    if data_config.SYSTEMTYPE == "MythVantage":
        setup_hobbit(systemconfig.get("UseHobbit"),
                    systemconfig.get("SystemType"),
                    systemconfig.get("dbhost"))
    #if data_config.SYSTEMTYPE == "LinHES":
        #setup_rrd(systemconfig.get("UseRRD"))

    #setup_evrouter(systemconfig.get("UseEvrouter"),
                #systemconfig.get("EvrouterConfig"),
                #systemconfig.get("TEMPLATES"))

    setup_DNSmasq(systemconfig.get("RunDHCP"),
                systemconfig.get("mythip"),
                systemconfig.get("mythgw"),
                systemconfig.get("mythdns"))

    setup_mythweb(systemconfig.get("UseMythWEB"))

    setup_dyndns(systemconfig.get("DDnsEnable"))
    logging.info("__End of advanced configuration\n")