#!/usr/bin/env python3
import os
import tempfile
import shutil
import glob
from subprocess import run

SOURCE       = os.environ.get("PLUGIN_SOURCE", ".")
TARGET       = os.environ['PLUGIN_TARGET']
HOST         = os.environ.get("PLUGIN_HOST", "")
PRE_COMMAND  = os.environ.get("PLUGIN_PRE", "")
POST_COMMAND = os.environ.get("PLUGIN_POST", "")

def is_target_http(target):
    return target.startswith("http://") or target.startswith("https://")

def apply_key_permissions(keyfile):
    os.chmod(keyfile, 0o600)
    if not os.name == "nt":
        return

    username = os.environ['USERNAME']
    users_directory = "C:\\Users"
    run(["Icacls", keyfile, "/c", "/t", "/Inheritance:d"])
    run(["TakeOwn", "/F", keyfile])
    run(["Icacls", keyfile, "/c", "/t", "/Grant:r", f"{username}:F"])
    run(["Icacls", keyfile, "/c", "/t", "/Remove:g", "Administrator", "Authenticated Users", "BUILTIN\\Administrators", "BUILTIN", "Everyone", "System", "Users"])
    for other_user in [user for user in os.listdir(users_directory) if not user == username]:
        run(["Icacls", keyfile, "/c", "/t", "/Remove:g", other_user])
    run(["Icacls", keyfile])

def run_command(host, command, auth):
    print(f">> [exec] {host} {command}")    
    run(["ssh", "-i", auth, "-o", "StrictHostKeyChecking=no", "-o", "PasswordAuthentication=no", host, "sh", "-c", command], check=True)

def make_parent_dirs(target, auth):
    if is_target_http(target):
        return

    (host, path) = target.split(":", 2)
    run(["ssh", "-i", auth, host, "mkdir", "-p", os.path.dirname(path)], check=True)

def deploy(source, target, auth):
    for source_file in glob.glob(source):
        deploy_file(source_file, target, auth)

def deploy_file(source_file, target, auth):
    print(f">> [deploy] {source_file} -> {target}")
    if is_target_http(target):
        run(["curl", "--user", auth, target, "--upload-file", source_file], check=True)
    else:
        run(["scp", "-i", auth, "-o", "StrictHostKeyChecking=no", "-o", "PasswordAuthentication=no", "-r", source_file, target], check=True)

temp_file_name = None
auth = None

if HOST:
    if is_target_http(HOST):
        TARGET = f"{HOST}/{TARGET}"
    else:
        TARGET = f"{HOST}:{TARGET}"
else:
    if is_target_http(TARGET):
        HOST = TARGET.split("/")[0]
    else:
        HOST = TARGET.split(":")[0]

try:
    if 'PLUGIN_KEY' in os.environ:
        with tempfile.NamedTemporaryFile(delete=False) as deploy_key:
            temp_file_name = deploy_key.name
            deploy_key.write(os.environ['PLUGIN_KEY'].encode())
            deploy_key.write(b"\n")
            deploy_key.close()

            apply_key_permissions(deploy_key.name)
            auth = deploy_key.name
    else:
        auth = os.environ['PLUGIN_AUTHENTICATION']

    if PRE_COMMAND:
        run_command(HOST, PRE_COMMAND, auth)

    #make_parent_dirs(TARGET, auth)
    deploy(SOURCE, TARGET, auth)

    if POST_COMMAND:
        run_command(HOST, POST_COMMAND, auth)
finally:
    if temp_file_name is not None:
        os.remove(temp_file_name)
