#!/usr/local/bin/python3

"""
EDSY was created using assets and imagery from Elite Dangerous, with the permission of Frontier Developments plc, for non-commercial purposes.
It is not endorsed by nor reflects the views or opinions of Frontier Developments and no employee of Frontier Developments was involved in the making of it.

Except where noted otherwise, all design, markup and script code for EDSY is copyright (c) 2015-2021 taleden
and is provided under a Creative Commons Attribution-NonCommercial 4.0 International License (http://creativecommons.org/licenses/by-nc/4.0/).

The Elite Dangerous game logic and data in this file remains the property of Frontier Developments plc, and is used here as authorized by
Frontier Customer Services (https://forums.frontier.co.uk/index.php?threads/elite-dangerous-media-usage-rules.510879/).
"""

import cgi, cgitb, os, requests, sys
from time import sleep
cgitb.enable()

LOCAL = ('REQUEST_URI' not in os.environ)
DEV = (not LOCAL) and os.environ['REQUEST_URI'].startswith('/dev/')

try:
	outHeaders = {
		'status': 500,
		'cache-control': 'no-cache,no-store,must-revalidate,private',
		'expires': 'Sat, 01 Jan 2000 00:00:00 GMT',
		'pragma': 'no-cache',
		'strict-transport-security': 'max-age=300; includeSubDomains', # max-age=31536000; preload
	}
	outBody = list()
	slug = ''
	if (not LOCAL) and os.environ['REQUEST_URI'].startswith('/dev/s/' if DEV else '/s/'):
		slug = os.environ['REQUEST_URI'][(7 if DEV else 3):]
	else:
		inForm = cgi.FieldStorage()
		slug = inForm.getfirst('slug') if ('slug' in inForm) else ''
	#if path/form
	if slug.startswith('v'):
		reqParams = {
			'format': 'simple',
			'shorturl': slug[1:],
		}
		req = requests.get('https://v.gd/forward.php', params=reqParams, timeout=10)
		if req.status_code == 502: # 502 Bad Gateway means rate limited
			sleep(5)
			req = requests.get('https://v.gd/forward.php', params=reqParams, timeout=10)
		#if 502
		if req.status_code == 200:
			url = req.text
			urltokens = url.split('/',3)
			if (len(urltokens) >= 3) and (urltokens[0] in {'http:','https:'}) and (urltokens[1] == '') and (urltokens[2] in {'edsy.org','www.edsy.org'}):
				outHeaders['status'] = 301
				outHeaders['location'] = url
			else:
				outHeaders['status'] = 400
				outHeaders['content-type'] = 'text/plain'
				outBody.append('invalid shortlink')
			#if edsy.org
		else:
			outHeaders['status'] = req.status_code
			outHeaders['content-type'] = req.headers['content-type']
			outBody.append(req.text)
		#if 200
	else:
		outHeaders['status'] = 400
		outHeaders['content-type'] = 'text/plain'
		outBody.append(('invalid' if slug else 'missing') + ' shortlink')
	#if slug
	print("%s%s\r\n%s" % (
			"\r\n".join(("%s: %s" % (key,val)) for key,val in outHeaders.items()),
			"\r\n" if outHeaders else "",
			"\n".join(outBody)
	), end="")
except:
	print("Status:500\r\nCache-Control: no-cache,no-store,must-revalidate,private\r\nExpires: Sat, 01 Jan 2000 00:00:00 GMT\r\nPragma: no-cache\r\nStrict-Transport-Security: max-age=300; includeSubDomains\r\nContent-type: text/html\r\n\r\n", end="")
	print(cgitb.html(sys.exc_info()))
#try/except
