#!/usr/bin/env python

# -*- coding: utf-8 -*-
"""
Created on Sun May  6 19:10:28 2018

@author: aslan.varoqua@duasamericasgroup.com
"""

import os
import subprocess, threading
from subprocess import Popen, PIPE, STDOUT
from flock import flock
import time
import datetime

now = datetime.datetime.now()
minusTwenty = now - datetime.timedelta(minutes = 10)

# globals
global start 
start = "-param start=" + str(now.isoformat()) 
global finish
finish = "-param finish=" + str(minusTwenty.isoformat())
global pcap 
pcap = "/src/p0f-input/input.pcap"
global processor 
processor = "-f pig/examples/device_fingerprint.pig"
global mv 
mv = 'mv'
global rm 
rm = 'rm'
global pig 
pig = 'pig'
global tcpdump 
dump = 'tcpdump'
global seconds 
seconds = '-G 30'
global iface 
iface = '-ni eno2'
global queue 
queue =  '/p0f-queue/'
global p0f_input 
p0f_input = '/p0f-input/input.pcap'
global landfill 
landfill = '-s0 -w /p0f-input/input.pcap'

def tcpdump():
   pcap = Popen([dump,iface,seconds,landfill],shell=True)
   pcap.communicate()
   pcap.kill()

def sweep():
   pcap = Popen([rm,p0f_input,mv,queue + "*",p0f_input],shell=True)
   pcap.communicate()
   pcap.kill()
    

def send2pig():
    try:
    	piggy = Popen([pig,processor,start,finish],shell=True)       
    	piggy.communicate()
    	piggy.kill()
    except:
    	print('could not access /p0f-input/input.pcap')
    	print('gracefully shutting down')
    	pass

def main():
    ## ========
    ## a message that there is a lock in place and exit.
    lock = flock('/src/packetpig/pig.lock', True).acquire()
    
    if lock:
    	try:
	    sweep()
	except:
	    print("nothing in queue - making new dump 20min")
	    tcpdump()
	send2pig() 
        
    else:
        print('someone else is working here!')

if __name__ == "__main__":

    main()
