#!/usr/bin/python
# import MySQL module
#jm
import MySQLdb
import sys
import getopt
import socket
import os
import time
import string
import glob
from string import letters
from string import digits

def INSERTCARD_INTOMYTH(Device,Driver,Cardvendor):
    global currenthostname
    print Device
    print Driver,
    print Cardvendor
    cursor = db.cursor()
    insert = "false"
    if Driver == "ivtv" :
        cardtype="MPEG"
        defaultinput="Tuner 1"
        insert="true"
    if Cardvendor ==  "pcHDTV HD3000 HDTV":
        insert="false"
        cardtype ="whocares"

        #print insert
    if insert == "true" :
        cursor.execute("INSERT INTO capturecard (videodevice,cardtype,defaultinput,hostname) VALUES(%s,%s,%s,%s);",(Device,cardtype,defaultinput,currenthostname))

def INSERTHDR_INTOMYTH(deviceid,tuner_number):
    cardtype='HDHOMERUN'
    defaultinput='MPEG2TS'
    global currenthostname
    print deviceid
    print cardtype
    print defaultinput
    print tuner_number
    cursor = db.cursor()
   #print insert
    cursor.execute("INSERT INTO capturecard (videodevice,cardtype,defaultinput,dbox2_port ,hostname) VALUES(%s,%s,%s,%s,%s);",(deviceid,cardtype,defaultinput,tuner_number,currenthostname))

def INSERTAUTOCARD():
    global cardlist
    global currenthostname
    # create a cursor
    cursor = db.cursor()


    for i in range( 1 , len(cardlist)):
        insert = "false"
#        print cardlist[i]
        Device=cardlist[i][0]
        Driver=cardlist[i][1]
        Cardvendor=cardlist[i][2]
        Businfo=cardlist[i][3]
        if Driver == "ivtv" :
            insert="true"
            devicestatus="unused"
        if Cardvendor ==  "pcHDTV HD3000 HDTV":
            insert="false"
            cardtype ="whocares"
        if Driver == "hdr":
            insert="true"
            devicestatus="unused"

        if insert == "true" :
            cursor.execute("delete from autocard where uniqid=%s;",(Businfo))
            if Driver=="hdr":
                Cardvendor="HDHOMERUN Tuner 1"
                cursor.execute("INSERT INTO autocard (dev,driver,description,uniqid,devicestatus,hostname) VALUES(%s,%s,%s,%s,%s,%s);",(Device,Driver,Cardvendor,Businfo,devicestatus,currenthostname))
                Cardvendor="HDHOMERUN Tuner 2"
                cursor.execute("INSERT INTO autocard (dev,driver,description,uniqid,devicestatus,hostname) VALUES(%s,%s,%s,%s,%s,%s);",(Device,Driver,Cardvendor,Businfo,devicestatus,currenthostname))

            else:
                cursor.execute("INSERT INTO autocard (dev,driver,description,uniqid,devicestatus,hostname) VALUES(%s,%s,%s,%s,%s,%s);",(Device,Driver,Cardvendor,Businfo,devicestatus,currenthostname))



def PRINTINFO():
    global cardlist

    for list in cardlist:
        if  list != "_placeholder_":
            print list
            #print "-------------"

def GATHER_HDR():
    global cardlist
    command="/usr/bin/hdhomerun_config --discover"
    results=os.popen(command,'r')
    line=results.readline()
    if line.strip().split()[0] == "no":
        print "HDHOMERUN not detected"
    else:
        print line
        hdrdevice=line.strip().split()[2]
        print hdrdevice
        Driver="hdr"
        Device=hdrdevice
        Cardtype="HDHOMERUN"
        Businfo=hdrdevice
        cardprops =  [Device,Driver , Cardtype , Businfo]
        cardlist.append(cardprops)


def GATHER_v4l_CARDS():
    global cardlist
    cardlist=["_placeholder_"]
   # print "Looking for v4l cards"
    try:
        filelist = os.listdir('/dev/v4l/')
    except OSError:
        filelist=" "
        #fakelist=['/dev/v4l/video3', 'ivtv', 'WinTV PVR 500 (unit #2)', '0000:04:09.0']
        #cardlist.append(fakelist)
    try:
        filelist = glob.glob("/dev/v4l/video?")
        Driver=""
        Cardtype=""
        Businfo=""
        numcards  = 0
        for Device in filelist:
            #print card
            numcards = numcards+1
            cmd = 'v4l2-ctl -D -d' + Device
            for line in os.popen(cmd).readlines():
                #print line
                pos = string.find(line,"Driver name")
                if pos >=0:
                    splitline= line.split(':')
                    Driver=splitline[1].strip()
                pos = string.find(line,"Card type")
                if pos >=0:
                    splitline= line.split(':')
                    Cardtype=splitline[1].strip()

                pos = string.find(line,"Bus info")
                if pos >=0:
                    splitline= line.split(':',1)
                    Businfo=splitline[1].strip()

            #print Device,Driver , Cardtype , Businfo,numcards
            cardprops =  [Device,Driver , Cardtype , Businfo]
            cardlist.append(cardprops)
    except IOError:
        print "no v4l cards found"
        sys.exit(2)


def WRITEUDEV_IVTV():
    global insertmyth
    cursor = db.cursor()
    #add ivtv,cid lookup loop through until empty.
    cursor.execute("select distinct(uniqid) from autocard where driver='ivtv' and devicestatus='will-add'")
    cidrows = cursor.fetchall()
    for row in cidrows:
        cid=row[0]
        cursor.execute("select dev,driver,description,devicestatus,hostname from  autocard where uniqid=%s limit 1;",(cid))
        result = cursor.fetchone()
        description=result[2]
        driver='DRIVERS==\"ivtv\"'
        ATTRNAME='ATTR{name}=="ivtv? encoder MPG"'
        KERNELS='KERNELS==\"'
        KERNELS+=cid
        KERNELS+="\""
        #filter out non digit or chars
        keep=letters.join(digits)
        description=filter(lambda c: c in keep, description)
        devnode="ivtv/"
        #devnode+=description + "_"
        udevcid=cid.partition(":")
        devnode+=udevcid[2]
        devnode+="_video"
        UDEV_RULE=driver +', '+ATTRNAME+', '+ KERNELS +', ' + 'NAME=\"' + devnode + '"'
        print "Here is the udev rule"
        print UDEV_RULE
        filename='/etc/udev/rules.d/11-ivtv-'+cid+'.rules'
        file = open(filename,'w')
        file.write(UDEV_RULE)
        if ( insertmyth == "true"):
            devnode="/dev/"+devnode
            INSERTCARD_INTOMYTH(devnode,"ivtv",description)
            cursor.execute("update autocard set devicestatus='done' where uniqid=%s;",(cid))
#now insert HDR
    cursor.execute("select distinct(uniqid),description from autocard where driver='hdr' and devicestatus='will-add'")
    cidrows = cursor.fetchall()
    for row in cidrows:
              if ( insertmyth == "true"):
                  deviceid=row[0]
                  #cardtype="HDHOMRUN"
                  #defaultinput="MPEG2TS"
                  dbox2_port=row[1]
                  tuner_number=dbox2_port.rpartition(' ')[2]
                  INSERTHDR_INTOMYTH(deviceid,tuner_number)
                  cursor.execute("update autocard set devicestatus='done' where uniqid=%s and description=%s;",(deviceid,dbox2_port))



def CLEARAUTOCARD():
    cursor = db.cursor()
    cursor.execute("delete from autocard")

def RELOADUDEV():
        print "relaoding udev rules"
        os.system('udevcontrol reload_rules')
        os.system('rmmod ivtv')
        os.system('udevtrigger')


def usage():
    print " -h   help"
    print " -g   gather and print out the found cards"
    print " -w   write out the udev rules"
    print " -i   insert cards into myth that are marked will-add(only used with -w)"
    print " -r   reload udev rules"
    print " -c   clear the autocard db"

def main(argv):
    global db
    global cardlist
    global currenthostname
    currenthostname=""
    writeudev="false"
    global insertmyth
    insertmyth ="false"

    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    try:
        cursor = db.cursor()
        cursor.execute("describe autocard;")
    except  MySQLdb.Error, e:
        cursor.execute("create table autocard(dev varchar(50),driver varchar(50),description varchar(50),uniqid varchar(50), devicestatus varchar(50),hostname varchar(50));")
        print "table created"

    if ( currenthostname == "" ):
         currenthostname = socket.gethostname()


    try:
        opts, args = getopt.getopt(argv, "hgwirc", ["help", "gathercards",  "writeudev" ,"insert" , "reloadudev" , "clearautocard"] )
    except getopt.GetoptError:
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
             usage()
             sys.exit()
        elif opt in ( "-g" , "--gathercards"):
             GATHER_v4l_CARDS()
             GATHER_HDR()
             INSERTAUTOCARD()
             PRINTINFO()
        elif opt in ("-w", "--writeudev"):
             writeudev="true"
        elif opt in ("-i", "--insert"):
             insertmyth="true"
        elif opt in ( "-r" , "--reloadudev"):
             RELOADUDEV()
        elif opt in ( "-c" , "--clearautocard"):
             CLEARAUTOCARD()


    if ( writeudev == "true"):
        WRITEUDEV_IVTV()






if __name__ == "__main__":
    main(sys.argv[1:])





#mysql>  create table autocard(dev varchar(50),driver varchar(50),description varchar(50),uniqid varchar(50), devicestatus varchar(50),hostname varchar(50));
#Query OK, 0 rows affected (0.14 sec)

#mysql> describe autocard;
#+--------------+-------------+------+-----+---------+-------+
#| Field        | Type        | Null | Key | Default | Extra |
#+--------------+-------------+------+-----+---------+-------+
#| dev          | varchar(50) | YES  |     | NULL    |       |
#| driver       | varchar(50) | YES  |     | NULL    |       |
#| description  | varchar(50) | YES  |     | NULL    |       |
#| uniqid       | varchar(50) | YES  |     | NULL    |       |
#| devicestatus | varchar(50) | YES  |     | NULL    |       |
#| hostname     | varchar(50) | YES  |     | NULL    |       |
#+--------------+-------------+------+-----+---------+-------+