#!/usr/bin/env python
# encoding: utf-8
"""
icap-safe-youtube.py

Created by Thomas Mangin on 2011-11-29.
Copyright (c) 2011-2013  Exa Networks. All rights reserved.
"""

import re
import sys

try:
	while True:
		line = sys.stdin.readline()
		method,uri,version = line.rstrip().split()
		if method != 'REQMOD':
			sys.stderr.write('ICAP METHOD not supported %s\n' % method)
			sys.stderr.flush()
		if version != 'ICAP/1.0':
			sys.stderr.write('ICAP version not supported %s\n' % version)
			sys.stderr.flush()

		client = ''
		while True:
			line = sys.stdin.readline().rstrip()
			if not line:
				break
			if line.startswith('Pragma: client='):
				client = line[15]
			last = line

		# we know ExaProxy send the Encapsulation as last parameter .. yes we do :)
		length = int(last.rstrip().split('=')[-1])
		_ = sys.stdin.read(length)
		upper = _.upper()

		if 'CONNECT ' in upper:
			headers = _ 
		elif 'youtube.' in _:
			headers = re.sub("([Cc]ookie:.*[;\\s])PREF=([^;]*)(.*)","\\1PREF=f2=8000000&\\2; \\3",_)
		else:
			headers = _

		reply = """\
ICAP/1.0 204 No Content
Encapsulated: res-hdr=0, null-body=%d

%s""" % (len(headers),headers)
		sys.stdout.write(reply)
		sys.stdout.flush()
except KeyboardInterrupt, e:
	sys.stderr.write('^C keyboard interrupt. exiting.\n')
	sys.stderr.flush()
except Exception, e:
	sys.stderr.write('CHILD FAILED %s\n' % str(e))
	sys.stderr.flush()
