#!/usr/bin/env python3

import os, sys, glob

def relpath(path, start):
    """Return a relative version of a path"""

    if not path:
        raise ValueError("no path specified")

    start_list = os.path.abspath(start).split(os.path.sep)
    path_list = os.path.abspath(path).split(os.path.sep)

    # Work out how much of the filepath is shared by start and path.
    i = len(os.path.commonprefix([start_list, path_list]))

    rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
    if not rel_list:
        return os.path.curdir
    return os.path.join(*rel_list)

if len(sys.argv) > 1:
	image = sys.argv[1]

if len(sys.argv) > 2:
	docpath = sys.argv[2] #os.path.dirname(sys.argv[2])
else:
	docpath = '.'

if len(sys.argv) > 3 and str.strip(sys.argv[3]):
	exts = [s.strip() for s in sys.argv[3].split(',')]
else:
	# Standard images for web
	exts = ['png', 'svg', 'jpg', 'jpeg']

exts = ['.' + e for e in exts]

def lookup(image):
	images = glob.glob(os.path.join(docpath, image))
	if not images:
		return
	elif len(images) == 1:
		return images[0]

	found = [os.path.splitext(s)[1] for s in images]
	for e in exts:
		if e not in found:
			continue
		return images[found.index(e)]
	else:
		return images[0]
i = lookup(image)
if not i:
	i = image
print((relpath(i, docpath)))
