# -*- coding: utf-8 -*-
import logging, mv_common
import os, re
from urllib2 import Request, urlopen, URLError, HTTPError

config_file = "mv_config"
data_config = __import__(config_file, globals(), locals(), [])

def setup_zip(MVROOT,zipcode):
    logging.debug("____Setting up the zipcode____")

    if zipcode:
        cmd="%s/bin/restore_default_settings.sh -c ZIP -c %s" %(MVROOT,zipcode)
        mv_common.runcmd(cmd)
        #Let's also speed things up for those in North America
        cmd="mkdir /usr/bin/perlbin/vendor/tv_grabbers_non_na"
        mv_common.runcmd(cmd)
        cmd="mv  /usr/bin/perlbin/vendor/tv_grab_*  /usr/bin/perlbin/vendor/tv_grabbers_non_na"
        mv_common.runcmd(cmd)
        cmd="mv  /usr/bin/perlbin/vendor/tv_grabbers_non_na/tv_grab_na*  /usr/bin/perlbin/vendor/"
        mv_common.runcmd(cmd)
    else:
        logging.debug("    Zipcode is not set")

    logging.debug("__End of zipcode\n")

def setup_tz(timezone,TEMPLATES):
    logging.info("____Setting up the timezone____")

    if not timezone:
        timezone="unknown"
    logging.info("    Setting timezone to %s",timezone)
    mv_common.remove_file("/etc/localtime")
    #try:
        #logging.debug("    Removing /etc/localtime")
        #os.remove("/etc/localtime")
    #except:
        #logging.debug("    Couldn't remove /etc/localtime")
        #pass

    srclink="/usr/share/zoneinfo/%s" %timezone
    logging.debug("    symlinking %s to /etc/localtime",srclink)
    try:
        os.symlink(srclink,"/etc/localtime")
    except:
        logging.critical("    Couldn't make symlink for /etc/localtime")
    cmd = '''sed -e "s/^TIMEZONE=.*$/TIMEZONE=\\"%s\\" /" /etc/rc.conf > $TEMPLATES/rc.conf''' %re.escape(timezone)
    mv_common.runcmd(cmd)

    if os.path.exists("/etc/php/php.ini"):
        logging.info("    Changing timezone for php")
        cmd = '''sed -i "s/^.*date.timezone.*$/date.timezone=%s/" ${BASE}/etc/php/php.ini''' %re.escape(timezone)
        mv_common.runcmd(cmd)

    mv_common.cp_and_log(TEMPLATES+"/rc.conf","/etc/rc.conf")
    logging.info("__End of timezone\n")

def setup_nfs(systemconfig):
    nfslist=[]
    logging.info("____Start of setup_nfs____")
    scrubnfs(systemconfig["TEMPLATES"])

    if systemconfig["HaveCentralNFS"] == "yes":
        logging.debug("    Using a Central NFS server")
        if systemconfig["NFSserver"] == "file:nfsmap":
        #if it's a file check for it, failure results in downloading attempt from MBE
            nfsmap_file=data_config.MYTHHOME+"/templates/nfsmap"
            if not os.path.exists(nfsmap_file):
                logging.debug("    Couldn't find local %s",nfsmap_file)
                logging.info("    Trying to download nfsmap from MBE")
                nfsmap_file = download_nfsmap(systemconfig["dbhost"])
            nfslist = process_nfsmap_file(nfsmap_file)
        # if it's an ip  parse ip and download file
        elif re.search(systemconfig["NFSserver"],":nfsmap"):
            ip=systemconfig["NFSserver"].split(":")[0]
            nfsmap_file = download_nfsmap(ip)
            nfslist = process_nfsmap_file(nfsmap_file)
        #else treat it as a single mount point
        else:
            item = (systemconfig["NFSserver"] , systemconfig["NFSmount"])
            nfslist.append(item)
    else:
        #if standalone or slave try to use MBE
        if systemconfig["SystemType"] == "Frontend_only" or systemconfig["SystemType"] == "Slave_Backend":
            item = (systemconfig["dbhost"] , data_config.DATAMOUNT)
            nfslist.append(item)
    setup_nfs_fstab(nfslist)
    logging.info("__End of nfs\n")

def setup_sleep(systemconfig):
    logging.debug("____Setting up sleep____")
    autoshutdown = systemconfig["AutoShutdown"]
    stime1 = systemconfig["Shutdowntime"]
    stime2 = systemconfig["Shutdowntime2"]
    cstime1=''

    if autoshutdown == "1" :
        if  not stime1 == "-1" :
            cstime1 = stime1
            cshutdown = cstime1
        if  not stime2 == "-1" :
            if cstime1 :
                cshutdown = "%s,%s" %(cstime1,stime2)
            else:
                cshutdown = stime2
        logging.debug("    Shutdown time at %s",cshutdown)
        cmd='''sed -e "s/HOUR/%s/g" %s/cron.template | crontab - -u mythtv''' %(cshutdown,systemconfig["TEMPLATES"])
        mv_common.runcmd(cmd)
    else:
        logging.info("    Shutdown not enabled")
        cmd='''sed -e "/00 HOUR.*/d" %s/cron.template | crontab - -u mythtv''' %systemconfig["TEMPLATES"]
        mv_common.runcmd(cmd)

    logging.debug("__End of  sleep\n")


def process_nfsmap_file(mapfile):
    logging.debug("   processing nfsmap file %s",mapfile)
    nfslist = []
    try:
        f = open(mapfile,"r")
        for line in f.readlines():
            if line.startswith("#"):
                continue
            item = line.split()
            if len(item) <= 1 :
                continue
            logging.debug("    %s",item)
            nfslist.append(item)
    except :
        logging.critical("Couldn't read file %s, or some other error",mapfile)
    return nfslist

def scrubnfs(templates):
    logging.info("    Scrubbing nfs")
    mv_common.cp_and_log("/etc/fstab",templates+"/fstab.conf.template")
    #used this sed cmd because it's clean and took me forever to figure out =)
    cmd='''sed '/^#STARTSCRUB.*$/,/^#ENDSCRUB.*$/d' %s/fstab.conf.template > /etc/fstab''' %templates
    mv_common.runcmd(cmd)

def download_nfsmap(ip):
    nfsmap_file="/tmp/nfsmap"
    myurl="http://%s:1337/templates/nfsmap" %ip
    req = Request(myurl)
    try:
        f = urlopen(req)
        logging.info("    downloading %s", myurl)
        local_file = open(nfsmap_file, "w")
        #Write to our local file
        local_file.write(f.read())
        local_file.close()
    #handle errors
    except HTTPError, e:
        logging.info("    File download failed")
        logging.debug("    %s", myurl)
        logging.debug("   HTTP Error: %s", e.code)
    except URLError, e:
        logging.info("    File download failed")
        logging.debug("   %s",myurl)
        logging.debug("   URL Error: %s ", e.reason)

    return nfsmap_file

def setup_nfs_fstab(nfslist):
    logging.info("    Adding nfs paths to fstab")
    try:
        f = open('/etc/fstab', 'a')
        line = "#STARTSCRUB --------------anything in this block will be scrubbed\n"
        f.write(line)
        for s, m in nfslist:
            line = "%s %s    nfs \n" %(s,m)
            logging.debug("    %s",line)
            f.write(line)
        line = "#ENDSCRUB\n"
        f.write(line)
        f.close()
    except:
        logging.critical("    *Couldn't open /etc/fstab for writing")
    logging.debug("   Done adding nfs paths to fstab")