#!/usr/bin/python
import sys,time,collections,os,signal
argc=len(sys.argv)
tmppath="/tmp/"
def printusage():
    print("""ifpy - show interface transfer rates with moving average
        usage: ifpy -[cnmx] [-i interval] [-s seconds] [-a samples] <interface>
        flags:
            -c : turn off color
            -n : adds newline at end of lines
            -m : csv output 
            -i <seconds> : interval between samples/updates (can be <1)
            -s <seconds> : seconds of samples to average
            -a <samples> : number of samples to average
            -x : output one value and exit uses /tmp/ifpytmp to store the previous sample
            -X : output one value and exit with newline seperator
            -S : output for use in screen hardstatus
            -w <widht> : constant width of <width> digits left of decimal
            default is -i 1 -s 5
        Created by oddbondboris report bugs to obbspam@gmail.com
            """)

def c_c(a,b):
        print()
        sys.exit()
signal.signal(signal.SIGINT, c_c)
def colored(txt,color,screen):
    cnames=[("red"),("green"),("yellow"),("blue"),("magenta"),("cyan")]
    if screen==0:
        ccodes=[("\033[31m"),("\033[32m"),("\033[33m"),("\033[34m"),("\033[35m"),("\033[36m")]
    else:
        ccodes=[("\005{r}"),("\005{g}"),("\005{y}"),("\005{b}"),("\005{m}"),("\005{c}")]

    try:
        if screen==0:
            return "%s%s%s"%(ccodes[cnames.index(color)],txt,"\033[0m")
        else:
            return "%s%s%s"%(ccodes[cnames.index(color)],txt,"")
    except:
        return txt
if argc<2:
    print("error: no interface given")
    printusage()
    sys.exit()
args=["iface","i","a","s","h","c","m","n","x","S","X","w"]
argvals=["",1.0,5,0,-1,-1,-1,-1,-1,-1,-1,0]
i=0
while i<argc:
    carg=sys.argv[i]
    clen=len(carg)
    if carg[0]=="-":
        argflag=carg[1:2]
        try:
            argindex=args.index(argflag)
        except:
            print("%s is not a valid flag"%argflag)
            printusage()
            sys.exit()
        if argvals[argindex]==-1:
            argval=1
            if clen>2:
                argflag2=carg[2:3]
                try:
                    argindex2=args.index(argflag2)
                except:
                    print("%s is not a valid flag"%argflag2)
                    printusage()
                    sys.exit()
                argvals[argindex2]=1
                if clen>3:
                    argflag3=carg[3:4]
                    try:
                        argindex3=args.index(argflag3)
                    except:
                        print("%s is not a valid flag"%argflag3)
                        printusage()
                        sys.exit()
                    argvals[argindex3]=1

                    
                    
        else:
            if clen==2:
                try:
                    argval=float(sys.argv[i+1])
                    i=i+1
                except ValueError:
                    print("error: -%s requires a numeric flag"%argflag)
                    sys.exit()
                except IndexError:
                    print("error: -%s requires a flag"%argflag)
                    sys.exit()
            else:
                try:
                    argval=float(carg[2:clen])
                except ValueError:
                   print("error: -%s requires a numeric flag"%argflag)
                   sys.exit()
                except IndexError:
                   print("error: -%s requires a flag"%argflag)
                   sys.exit()
        argvals[argindex]=argval
    else:
        argvals[0]=sys.argv[i]
    i=i+1
if argvals[0]=="":
    print("need an interface")
    sys.exit()
interface=argvals[0]
interval=argvals[1]
avg=int(argvals[2])
seconds=argvals[3]
if argvals[4]==1:
    printusage()
    sys.exit()

running=1
sol="\r"
rxstart=""
rxformat="RX:%.2fKB/s"
rxcolor='green'
seperator=" "
txstart=""
txformat="TX:%.2fKB/s"
txcolor='red'
eol="    "
tmp=0
screen=0
flen=int(argvals[10]+6)
if argvals[5]==1:
    rxcolor=''
    txcolor=''
if argvals[6]==1:
    rxformat="%f"
    txformat="%f"
    rxcolor=''
    txcolor=''
    seperator=","
    flen=0
    sol=""
    eol="\n"
if argvals[7]==1:
    sol=""
    eol="\n"
if argvals[8]==1:
    rxstart="D"
    txstart="U"
#    rxstart=u'\u2193'
#    txstart=u'\u2191'
    rxformat=":%.2fK"
    seperator=" "
    txformat=":%.2fK"
    tmp=1
    oneshot=1
    flen=17
    eol="\n"
else:
    oneshot=0
if argvals[9]==1:
#    rxstart=u'\u2193'
#    txstart=u'\u2191'
#    rxstart="\\/"
#    txstart="/\\"
    rxstart="D"
    txstart="U"
    rxformat=":%.2fK"
    rxcolor='green'
    seperator=" "
    txformat=":%.2fK"
    txcolor='red'
    eol="\n"
    screen=1
if argvals[10]==1:
    sol=""
    rxstart="Rx"
    txstart="Tx"
#    rxstart=u'\u2193'
#    txstart=u'\u2191'
    rxformat=":%.2fKB/s"
    seperator="\n"
    txformat=":%.2fKB/s"
    tmp=1
    oneshot=1
    flen=17
    eol="\n"


if seconds!=0:
    avg=round(seconds/interval)
avg=avg+1
ifpath="/sys/class/net/%s/statistics/"%interface
try:
    f=open("%s../uevent"%ifpath,'r')
    f.close()
except:
    print("can't find interface %s "%interface)
    printusage()
    sys.exit()
txfile=open("%stx_bytes"%ifpath,'r')
rxfile=open("%srx_bytes"%ifpath,'r')
rxscale=1000
txscale=1000
txbuf=collections.deque('',avg)
rxbuf=collections.deque('',avg)
if tmp==0:
    nti=time.time()
    txbuf.appendleft((int(txfile.read()),nti))
    rxbuf.appendleft((int(rxfile.read()),nti))
else:
    try:
        tfile=open("%s/ifpytmp"%tmppath,'r+')
    except IOError as e:
        code=e.errno
        if code==13:
            print ("bad temp permissions")
        elif code==2:
            print ("no temp file yet : making one")
            try:
                tfile=open("%s/ifpytmp"%tmppath,'w')
                tfile.write("1")
                tfile.close()
                tfile=open("%s/ifpytmp"%tmppath,'r+')
                print "File created Successfully"
            except IOError as e:
                print ("error %d: %s"%(e.errno,e.strerror))            
                sys.exit()

    tf=tfile.read().split(",")
    if len(tf)==1:
        nti=time.time()
        nti=nti+1
        txbuf.appendleft((int(txfile.read()),nti))
        rxbuf.appendleft((int(rxfile.read()),nti))
    elif len(tf)==3:
        nti=int(tf[0])
        txbuf.appendleft((int(tf[1]),nti))
        rxbuf.appendleft((int(tf[2]),nti))




while running>0:
    if tmp==0:
        time.sleep(interval)
    rxfile.seek(0)
    txfile.seek(0)
    nti=time.time()
    newtx=int(txfile.read())
    newrx=int(rxfile.read())
    txbuf.appendleft((newtx,nti))
    rxbuf.appendleft((newrx,nti))
    oldtx=txbuf[-1]
    oldrx=rxbuf[-1]
    txavg=(newtx-oldtx[0])/(nti-oldtx[1])/txscale
    rxavg=(newrx-oldrx[0])/(nti-oldrx[1])/rxscale
    #sys.stdout.write((u"%s%s%s%s%s"%(sol,colored(u"%s%s"%(rxstart,rxformat%rxavg),rxcolor,screen),seperator,colored(u"%s%s"%(txstart,txformat%txavg),txcolor,screen),eol)).ljust(flen))
    sys.stdout.write(("%s%s%s%s%s"%(sol,colored(("%s%s"%(rxstart,rxformat%rxavg)).ljust(flen),rxcolor,screen),seperator,colored(("%s%s"%(txstart,txformat%txavg)).ljust(flen),txcolor,screen),eol)).ljust(flen))
    sys.stdout.flush()
    running=running-oneshot


if tmp==1:
    tfile.seek(0)
    nti=time.time()
    tfile.write("%i,%i,%i"%(nti,newtx,newrx))


