#!/usr/bin/python
"""
Script que ha de substituir l'anterior galeria, per poder fer la migracio a flickr
Necessita el fitxer infos.txt que conte les dades de les fotos que s'han pujat
"""

import cgi
import sys

form = cgi.FieldStorage()
if form.has_key('mode'):
	mode = form["mode"].value
	album = form["album"].value
	# el album de despedida de inlander esta malament. s'ha d'arreglar a ma
	if album == '/fotos/200310_24_despedida_inlander':
		album = '/fotos/20031024_despedida_inlander'

	if form.has_key('picture'):
		picture = form['picture'].value.replace('SMALL','')
	if form.has_key('Width'):
		width = form['Width'].value
	else:
		width = ""
else:
	print "Status: 301 Moved Permanently"
	print "Location: http://www.fr3nd.net/cgi-bin/photo/index2.cgi\n\n"
	sys.exit()

# mirem si hi ha un album. Si no hi ha cap, enviem als sets de flicker o al antic software segons correspongui

try:
	photoset = album.split('/')[2]
except:
	pass

f = open('infos.txt', 'r')

for line in f:
	props = line.split(':')
	try:
		if photoset == props[0]:
			if mode == 'viewpicture':
				if picture.split('.')[0] == props[1]:
					print "Status: 301 Moved Permanently"
					header = "Location: http://flickr.com/photos/fr3nd/" + props[3] + "/\n\n"
					print header
					sys.exit()
			elif mode == 'view':
				print "Status: 301 Moved Permanently"
				header = "Location: http://flickr.com/photos/fr3nd/sets/" + props[5] + "/\n\n"
				print header
				sys.exit()
			elif mode == 'rewrite':
				if picture.split('.')[0] == props[1]:
					print "Status: 301 Moved Permanently"
					header = "Location: http://static.flickr.com/" + props[2] + "/" + props[3] + "_" + props[4]
					if width == '320':
						header = header + "_m"
					elif width == '640':
						pass
					elif width == '800':
						pass
					elif width == '100' or width == 'thumbnails' or width == 'thumbnail':
						header = header + "_t"
					header = header + ".jpg\n\n"
					print header
					sys.exit()
	except:
		break

# si no s'ha trovat la correspondencia enviem al software antic
if mode == 'viewpicture':
	print "Status: 301 Moved Permanently"
	print "Location: http://www.fr3nd.net/cgi-bin/photo/index2.cgi?mode=" + mode + "&album=" + album + "&picture=" + picture + "\n\n"
elif mode == 'view':
	if album == '/fotos':
		print "Status: 301 Moved Permanently"
		print "Location: http://flickr.com/photos/fr3nd/sets/\n\n"
	else:
		print "Status: 301 Moved Permanently"
		print "Location: http://www.fr3nd.net/cgi-bin/photo/index2.cgi?mode=" + mode + "&album=" + album + "\n\n"
sys.exit()

