#!/usr/bin/env python3

# this program is fucking awful god damn

import argparse
import os
import hashlib
import sys

SSHKEYTAIL = "/.ssh/doggirlcdn.key" # THIS IS THE NAME OF YOUR KEY

DESTDIR = ":/srv/cdn/" # This is not good..
PRIVDIR = "private/"
PUBLDIR = "public/"
#LOCALURL = "FLKR-261801.attlocal.net"
LOCALURL = "192.168.1.90"
REMOTEURL = "cdn.doggirl.online" 
SSHPORT = "22" # This is also not good..
CDNHOST = "cdn"

def parseArgs():
    if len(sys.argv) < 2: 
        return None
    parser = argparse.ArgumentParser(prog="dogupload",description="Cloud storage but for dogs!", epilog="If there are any problems with this script just dm caroline about it and she\'ll try to fix it :3",add_help=True) #, formatter_class=argparse.MetavarTypeHelpFormatter)
    parser.add_argument("-l", "--local", help="Sends file over local network", action="store_true")
    parser.add_argument("-q", "--quiet", help="Run in quiet mode | TODO", action="store_true")
    parser.add_argument("-N", "--no-rename", help="Do not auto-rename the file", action="store_true")
    parser.add_argument("-n", "--name", help="Set the name of the output file")
    parser.add_argument("-p", "--public", help="Send the file to public storage", action="store_true")
    parser.add_argument("input_file", type=str)

    return parser.parse_args()

def httpizeStr(s: str):
    # Hopefully replacing all %'s first will remove the possibility of replacing the '%' in '%20'
    specialchars = [ '%', ' ', '!', '\"', '#', '$', '&', '\'', '(', ')', '+', ',', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '`', '{', '|', '}', '~' ]
    specialcharcodes = [ '%24', '%20', '%21', '%22', '%23', '%25', '%26', '%27', '%28', '%29', '%2B', '%2C', '%2F', '%3A', '%3B', '%3C', '%3D', '%3E', '%3F', '%40', '%5B', '%5C', '%5D', '%5E', '%60', '%7B', '%7C', '%7D', '%7E' ]
    for i in range(len(specialchars)):
        if specialchars[i] in s:
            print("string contains char `" + specialchars[i] + "`")
            s = s.replace(specialchars[i], specialcharcodes[i])
            print("post replacement: " + s)
    return s

def fileSend(src,dest):
    sshkey = str(os.getenv("HOME") + SSHKEYTAIL)
    # in the future you could maybe put like a little 
    pid = os.fork()
    if pid != 0:
        print("\x1b[33mINFO\x1b[0m: Waiting...")
        _, waitres = os.waitpid(pid, 0)

        return
    else:
        os.execlpe("scp", "scp", "-q", "-P", SSHPORT, "-i", sshkey, src, dest, os.environ)
    return

def main():
    args = parseArgs()
    if args is None or args.input_file is None:
        print("\x1b[31mERROR\x1b[0m: No file provided")
        return

    dest = ""
    if args.local: 
        print("\x1b[33mINFO\x1b[0m: Sending file locally")
        dest = CDNHOST + "@" + LOCALURL
    else:
        dest = CDNHOST + "@" + REMOTEURL
    dest = dest + DESTDIR

    if args.public:
        dest = dest + PUBLDIR
    else:
        dest = dest + PRIVDIR

    dest_fname = ""
    if args.no_rename:
        dest_fname = args.input_file
    elif args.name:
        dest_fname = args.name
    else:
        extidx = str(args.input_file).rfind('.')
        ext = ""
        if extidx != -1:
            # HOLY SHIT I FUCKING HATE THIS LANGUAGE!!!!!!
            ifs = str(args.input_file)
            ext = ifs[extidx:len(ifs)]
            pass
        else:
            ext = ".txt"

        dest_fname =  hashlib.md5(open(args.input_file, 'rb').read()).hexdigest() + ext  # this is really slow and bad... esp for big files...
    dest = dest + dest_fname

    fileSend(args.input_file,dest)

    dest_fname = httpizeStr(dest_fname)

    print("\x1b[32mSUCCESS\x1b[0m: File should exist at address `https://" + REMOTEURL + "/" + dest_fname + "`")

    pass

if __name__ == "__main__":
    main()
    pass
