#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
#    OpenAirInterface
#    Copyright(c) 1999 - 2014 Eurecom
#
#    OpenAirInterface is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#
#    OpenAirInterface is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with OpenAirInterface.The full GNU General Public License is
#    included in this distribution in the file called "COPYING". If not,
#    see <http://www.gnu.org/licenses/>.
#
#   Contact Information
#   OpenAirInterface Admin: openair_admin@eurecom.fr
#   OpenAirInterface Tech : openair_tech@eurecom.fr
#   OpenAirInterface Dev  : openair4g-devel@eurecom.fr
#
#   Address      : Eurecom, Campus SophiaTech, 450 Route des Chappes, CS 50193 - 06904 Biot Sophia Antipolis cedex, FRANCE
#
################################################################################
import sys
import subprocess
import re
import socket
import datetime
from datetime import date
import os, errno
import argparse




parser = argparse.ArgumentParser()
parser.add_argument("--pcap_file", "-p", type=str,help="input pcap file to be translated")
args = parser.parse_args()

pcap_file = args.pcap_file.strip()

pcap_dissected_file = subprocess.check_output(["tshark", '-V', '-r' , pcap_file], stderr=subprocess.STDOUT)
pcap_hex_file = subprocess.check_output(["tshark", '-x', '-O', 'sctp', '-r', pcap_file])
pcap_dissected_list = []

# split file content in lines
lines = pcap_dissected_file.splitlines()
message     = {}
item_index  = 0;
item_string = " "
fsm_state="search_frame"
for line in lines:
    print ("INPUT LINE:  %s " % line)
    line = line.strip()
    if line != "":       
        if fsm_state == "search_frame":
            if line.startswith("Frame"):
                message = {}
                partition = line.split(' ',3)
                message['frame'] = int(partition[1].strip(':'))
                fsm_state = "search_ip"
                print("Found Frame %d" % (message['frame']))
                
        elif fsm_state == "search_ip":
            if line.startswith("Internet Protocol Version"):
                fsm_state = "fill_ip"
                message['ip_fields'] = 0
                print("Found in Frame %d IP" % (message['frame']))

        elif fsm_state == "fill_ip":
            if line.startswith("Header length"):
                partition = line.split(' ',4)
                message['ip_header_length'] = int(partition[2])
                message['ip_fields'] += 1
                print("Found in Frame %d IP header length %d" % (message['frame'], int(partition[2])))
            if line.startswith("Total Length"):
                partition = line.split(' ',4)
                message['ip_total_length'] = int(partition[2])
                message['ip_fields'] += 1
                print("Found in Frame %d IP Total Length %d" % (message['frame'], int(partition[2])))
            if line.startswith("Protocol"):
                partition = line.split(' ',4)
                if partition[1] != "SCTP":
                    print("Error did not found in Frame %d SCTP" % (message['frame'])))
                    fsm_state="search_frame"
                    continue
                else:
                    message['ip_protocol'] = partition[1]
                    message['ip_fields'] += 1
                    print("Found in Frame %d SCTP" % (message['frame'])))
            if message['ip_fields'] == 3:
                fsm_state = "search_sctp"
                print("in Frame %d searching S1AP" % (message['frame'])))
                        
        elif fsm_state == "search_sctp":
            if line.startswith("Internet Protocol Version"):
                fsm_state = "fill_sctp"
                message['sctp_fields'] = 0
                
        elif fsm_state == "fill_sctp":
            if line.startswith("Source port"):
                partition = line.split(' ',4)
                message['Source port'] = int(partition[2])
                message['sctp_fields'] += 1
            elif line.startswith("Destination port"):
                partition = line.split(' ',4)
                message['Destination port'] = int(partition[2])
                message['sctp_fields'] += 1
            elif line.startswith("Chunk length"):
                partition = line.split(' ',4)
                message['Chunk length'] = int(partition[2])
                message['sctp_fields'] += 1
            elif line.startswith("Stream Identifier"):
                partition = line.split(' ',4)
                message['Stream Identifier'] = int(partition[2])
                message['sctp_fields'] += 1
            elif line.startswith("Stream sequence number"):
                partition = line.split(' ',4)
                message['Stream sequence number'] = int(partition[3])
                message['sctp_fields'] += 1
            elif line.startswith("Chunk padding"):
                partition = line.split(' ',4)
                message['Chunk padding'] = int(partition[2])
                message['sctp_fields'] += 1
            if message['sctp_fields'] == 6:
                fsm_state = "search_s1ap"
                
        elif fsm_state == "search_s1ap":
            if line.startswith("S1 Application Protocol"):
                fsm_state = "fill_s1ap"
                message['s1ap_fields'] = 0
                print("in Frame %d Filling S1AP" % (message['frame'])))
                        
        elif fsm_state == "fill_s1ap":
            if line.startswith("S1AP-PDU:"):
                partition = line.split(' ')
                message['Pdu'] = partition[1]
                message['s1ap_fields'] += 1
            elif line.startswith("procedureCode:"):
                partition = line.split(' ')
                message['procedureCode:'] = partition[1]
                message['s1ap_fields'] += 1
            elif line.startswith("protocolIEs"):
                partition = line.split(' ')
                message['protocolIEs'] = int(partition[1])
                message['items'] = {}
            elif line.startswith("Item"):
                partition = line.split(' ')
                item_index  = partition[1].trim(':')
                item_string = partition[2]
                message['items'][item_string] = ' '
                print("Found in Frame %d S1AP Item %d %s" % (message['frame'], item_index, item_string)))
                if item_string == id-E-RABToBeSetupListCtxtSUReq:
                elif item_string == id-E-RABToBeSetupListCtxtSUReq:
            elif line.startswith("nAS-PDU"):
                partition = line.split(' ')
                nas_bytes = partition[1].trim('.')
                message['items'].append
                print("Found in Frame %d Stream sequence number" % (message['frame'], int(partition[3])))

            if message['s1ap_fields'] == 6:
                pcap_dissected_list.append(message)
                fsm_state = "search_frame"

for message in pcap_dissected_list:
    print("Message:\n" )
    print("    %s" % (message))

lines = pcap_hex_file.splitlines()
message = {}
message_index = 0
fsm_state="search_frame"
for line in lines:
    print ("INPUT LINE:  %s " % line)
    line = line.strip()
    if line != "":       
        if fsm_state == "search_frame":
            if line.startswith("Frame"):
                partition = line.split(' ',3)
                fsm_state = "search_s1ap"
                                
        elif fsm_state == "search_s1ap":
            if line.startswith("S1 Application Protocol"):
                fsm_state = "fill_s1ap"
                message = pcap_dissected_list[message_index]
                message['s1ap_byte_offset'] = 0
                message['dumped'] = []
                message_index += 1
                        
        elif fsm_state == "fill_s1ap":
            if not line.startswith("Frame"):
                bytes = line.split(' ')
                byte_index = int(bytes[0],16)
                if byte_index ==  message['s1ap_byte_offset']:
                    message['s1ap_byte_offset'] += 16
                    for byte in bytes:
                        message['dumped'].append(byte)
                        message['s1ap_byte_offset'] += 1
                else:
                    fsm_state="search_frame"
            
print ("  %s " % ( pcap_dissected_list ) )

