#!/usr/bin/python

import os
import sys
import argparse
from django.core.exceptions import ValidationError

# django setup
DJANGO_SETTINGS_MODULE = 'settings'
DJANGO_PROJECT_PATH = os.path.dirname(sys.argv[0]) + '/web'
sys.path.insert(1, DJANGO_PROJECT_PATH)
os.environ['DJANGO_SETTINGS_MODULE'] = DJANGO_SETTINGS_MODULE
from web.postkey.models import i2phost
from web.lib.validation import validate_hostname
from web.lib.validation import validate_b64hash

# parse command line options
parser = argparse.ArgumentParser(
		description='Hosts injector for py-i2phosts.',
		epilog='Report bugs to http://zzz.i2p/topics/733')
parser.add_argument('-f', '--file', default=os.environ['HOME'] + '/.i2p/hosts.txt', dest='hostsfile',
		help='hosts.txt for parsing')
parser.add_argument('-d', '--description', default='Auto-added from external hosts.txt',
		help='provide custom description message')
parser.add_argument('-s', '--supress', action='store_true',
		help='supress warnings about already existed hostnames')
args = parser.parse_args()

f = open(args.hostsfile, 'r')
for line in f:
	# ignore comments and empty lines
	if line.startswith('#') or line.isspace():
		continue
	if line.find('=') == -1:
		sys.stderr.write('Invalid line: %s\n' % line)
		continue
	# strip trailing '\n'
	line = line.rstrip('\n')
	entry = line.split('=')
	try:
		hostname = validate_hostname(entry[0])
		base64 = validate_b64hash(entry[1], check_uniq=False) # don't require uniqueness
	except ValidationError, e:
		sys.stderr.write('validation error: %s: %s\n' % (e, line))
	else:
		# Check for already existed hosts in database to avoid unneeded INSERTs
		# beacuse they will fail anyway.
		qs = i2phost.objects.filter(name=hostname)
		if qs.exists():
			if not args.supress:
				print 'Host %s already exists' % hostname
		else:
			print 'Adding %s' % hostname
			host = i2phost(name=hostname, b64hash=base64,
					description=args.description,
					activated=True, external=True)
			host.save()
f.close()