#!/usr/bin/env python3

import os
import sys
import magic
import subprocess
import urllib.request
import tempfile

# Getting what's needed
path = sys.argv[1]

# Getting the MIME type
ishttp = path.startswith('http')

buf = None
if ishttp:
    buf = urllib.request.urlopen(path)
    chunk = buf.read(1024)
    mime = magic.from_buffer(chunk, mime=True)
else:
    assert os.path.isfile(path), f"Not a file: {path}"
    path = os.path.realpath(path)
    mime = magic.from_file(path, mime=True)
mime = tuple(mime.split('/'))
assert len(mime) == 2

graphical = not not os.environ.get('DISPLAY')

# Some energumens
if mime[0] == "application" and mime[1] in ("json", "javascript"):
    mime = ("text", mime[1])

# Determine stuff
ex = None  # Executable needed to open the file
forcelocal = False  # If we need to copy the file locally before opening it
isterm = False # Executable should run in a terminal

if mime[0] == "text":
    if not ishttp:
        ex = os.environ.get('VISUAL' if graphical else 'EDITOR', None)
        isterm = True
elif mime[0] == "image":
    ex = "feh"
elif mime[0] in ("audio", "video"):
    ex = "mpv"
    isterm = True
elif mime == ("application", "pdf"):
    ex = "llpp.inotify"
    forcelocal = True

# Open stuff
tmp = None
if ex:
    if forcelocal and ishttp:
        tmp = tempfile.NamedTemporaryFile(prefix='o')
        tmp.write(chunk)
        tmp.write(buf.read())
        path = tmp.name
else:
    ex = 'xdg-open'
    if ishttp:
        ex = os.environ.get('BROWSER', ex)
if buf:
    buf.close()

# TODO Launch a new terminal window for some

p = subprocess.run([ex, path])
if tmp:
    tmp.close()
sys.exit(p.returncode)