#!/usr/bin/env python
from __future__ import print_function
import os , sys , json
from tempfile import mkstemp
from jenkins_callback import build_jobs

print ("Content-Type: text/html\n")

BASE_DIRECTORY = "/data"

#check signature function
def check_signature(data, repo_config):
  return True

#check source ip in white list fucntion
def check_ip():
  try:
    ip_net = open(BASE_DIRECTORY+'/sdt/cmsrep.txt','r').read().split('\n')[0].strip()
  except Exception as e:
    print ("Unable to read cmsrep hook meta information, using hard coded value")
    ip_net ="188.184.102.160/32"

  ip, mask = ip_net.split('/')
  mask = int(mask)
  ip = ''.join(["{0:08b}".format(int(i)) for i in ip.split('.') ])[0:mask]
  if 'HTTP_X_FORWARDED_FOR' in os.environ and os.environ['HTTP_X_FORWARDED_FOR']!='':
    src_ip = ''.join([ "{0:08b}".format(int(i)) for i in os.environ['HTTP_X_FORWARDED_FOR'].split('.')])[0:mask]
  else:
    src_ip = ''.join([ "{0:08b}".format(int(i)) for i in os.environ['REMOTE_ADDR'].split('.')])[0:mask]
  return ip == src_ip

data = sys.stdin.read()
try:
  payload = json.loads(data)
except Exception as e:
  print ("Invalid data, can not read json input")
  sys.exit()

if not check_ip():
  print ("Invalid IP")
  sys.exit()

sys.path.insert(0,os.path.join(BASE_DIRECTORY,"sdt/cms-bot"))
import repo_config

if not check_signature(data, repo_config):
  print ("Invalid or wrong signatures")
  sys.exit()

xparam = []
for k in ["repository", "architecture", "payload_uri"]:
  if not k in payload:
    print ("Invalid data: Missing key %s" % k)
    sys.exit()
  xparam.append({"name":k.upper(),  "value":payload[k]})

build_jobs(repo_config.JENKINS_SERVER, [(json.dumps({"parameter":xparam}),"cmsrep-webhook")])
