#!/bin/bash /usr/scripts/python.sh
import socket
import struct
import time
import pickle
import os

import gestion.config.tv

MCAST_GRP = gestion.config.tv.SAP_MCAST_GRP # sap.mcast.net
MCAST_PORT = gestion.config.tv.SAP_MCAST_PORT
timeout=60
path = gestion.config.tv.SAP_FILE_TXT
pickeled_path = gestion.config.tv.SAP_FILE_PIC

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)

sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

service={}
service_simple={}

start=time.time()
while True:
  msg=sock.recv(10240).split('\r\n')
#  print msg
  s=None
  ip=None
  for line in msg[:-1]:
      (tag, value) = line.split('=', 1)
      #print (tag, value)
      if tag=='s':
          s=value
      if tag=='c':
          ip=value.split(' ')[2].split('/')[0]
      if tag=='a' and value.startswith('x-plgroup:'):
          group=value[10:]
  service_simple[s]=ip
  try:
      service[group][s]=ip
  except KeyError:
      service[group]={s:ip}
#  print "%s: %s" % (s, ip)
  if time.time() - start > timeout:
      break

f=open(path, 'w')
l=service_simple.items()
l.sort()
for (name, ip) in l:
    f.write("%s:%s\n" % (name, ip))
f.close()

pickle.dump(service, open(pickeled_path + '.tmp', 'w'))
os.rename(pickeled_path + '.tmp', pickeled_path)
