#!/usr/bin/env python3

# Copyright (c) 2021-2023 Amin Bandali <[email protected]>
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.

import os
from http.server import SimpleHTTPRequestHandler
import socketserver
import sys

try:
   PORT = int(os.getenv('PORT', 8000))
except ValueError:
   print('PORT must be in integer')
   exit(1)

ADDR = os.getenv('ADDR', '127.0.0.1')

class HttpRequestHandler(SimpleHTTPRequestHandler):
   extensions_map = dict(SimpleHTTPRequestHandler.extensions_map)
   extensions_map.update({'': 'text/plain;charset=UTF-8'})
   extensions_map.update({'.txt': 'text/plain;charset=UTF-8'})
   extensions_map.update({'.bib': 'text/plain;charset=UTF-8'})
   extensions_map.update({'.tex': 'text/plain;charset=UTF-8'})
   extensions_map.update({'.org': 'text/plain;charset=UTF-8'})

   def do_GET(self): # -> None
       if not os.path.isfile(os.getcwd() + self.path):
           exts = ['html', 'txt']
           for ext in exts:
               p = ".".join((self.path, ext))
               if os.path.isfile("".join((os.getcwd(), p))):
                   self.path = p
                   break
       super().do_GET()

class ReuseAddrTCPServer(socketserver.TCPServer):
   allow_reuse_address = True

def main(): # -> int
   with ReuseAddrTCPServer((ADDR, PORT), HttpRequestHandler) as httpd:
       try:
           print("listening on {}:{}".format(ADDR, PORT))
           httpd.serve_forever()
       except KeyboardInterrupt:
           pass
       except Exception as e:
           logger.exception(e)
   return 0

if __name__ == '__main__':
   sys.exit(main())