#!/usr/bin/env python

# CHECKr BiTCH

import os
import sys
import re
import csv

http301 = re.compile('^HTTP/1\.1 301')
http200 = re.compile('^HTTP/1\.1 200')
location = re.compile('Location: (.*)$', re.MULTILINE)
options = {
    'verbose': False,
    'old-prefix': '',
    'new-prefix': '',
}


def check(original, destination):
    response = os.popen('curl -s -k -I -L "%s"' % original, 'r').read()
    response_list = response.split("\r\n\r\n")
    final_redirect = ''
    for i in response_list:
        if http301.search(i):
            final_redirect = i
        elif http200.search(i):
            break
        else:
            print original, destination, response
            return False

    location_match = location.search(final_redirect)
    assert location_match, "There is something wrong with the regex"

    if location_match.group(1).strip() == destination:
        if options['verbose']:
            print '%s => %s' % (original, destination)
        return True
    else:
        print response
        return False


if __name__ == '__main__':
    input_file = sys.stdin
    sys.argv.pop(0)

    for arg in sys.argv:
        if arg == '-v' or arg == '--verbose':
            options['verbose'] = True
        elif arg == '-h' or arg == '--help':
            pass
        elif arg.startswith('--old-prefix='):
            options['old-prefix'] = arg.partition('=')[2]
        elif arg.startswith('--new-prefix='):
            options['new-prefix'] = arg.partition('=')[2]

    csv_file = csv.reader(input_file)

    for row in csv_file:
        if row and not check(options['old-prefix'] + row[0].strip(), options['new-prefix'] + row[1].strip()):
            print row
            sys.exit(1)
    sys.exit(0)
