import tempfile
import sys
from ssl import get_default_verify_paths

globals().update(config)

local_path = Path(local_file)
tempdir = tempfile.mkdtemp()
upload_done = Path(tempdir, f"{local_path.name}.uploaded")
checksum_file = Path(tempdir, f"{local_path.name}.sha256")
checksum_verified = Path(tempdir, f"{local_path.name}.verified")

remote_dest = f"{RCLONE_REMOTE}:{bucket}/{remote_path}"
remote_parent = f"{RCLONE_REMOTE}:{bucket}/{str(Path(remote_path).parent)}"
remote_filename = Path(remote_path).name
remote_include = f"/{remote_filename}"

# FIXME debugging SSL certificate path
openssl_capath_env = get_default_verify_paths().openssl_capath_env
logger.error(f"Debug. openssl_capath_env variable name: {openssl_capath_env}")
openssl_capath_env_value = os.getenv(openssl_capath_env, None)
logger.error(f"Debug. openssl_capath_env value:         {openssl_capath_env_value}")


envvars:
    f"RCLONE_CONFIG_{RCLONE_REMOTE}_TYPE",
    f"RCLONE_CONFIG_{RCLONE_REMOTE}_PROVIDER",
    f"RCLONE_CONFIG_{RCLONE_REMOTE}_ACCESS_KEY_ID",
    f"RCLONE_CONFIG_{RCLONE_REMOTE}_SECRET_ACCESS_KEY",
    f"RCLONE_CONFIG_{RCLONE_REMOTE}_ENDPOINT",
    openssl_capath_env,


rule generate_checksum:
    input:
        file=local_path,
    output:
        checksum=checksum_file,
    params:
        remote_filename=remote_filename,
    shell:
        "sha256sum {input.file} | sed 's|  .*|  {params.remote_filename}|' > {output.checksum}"


rule upload_file:
    input:
        file=local_path,
    output:
        done=touch(upload_done),
    params:
        remote_dest=remote_dest,
    shell:
        "rclone copyto "
        "{input.file} "
        "{params.remote_dest} "
        "--checksum "
        "--check-first "
        "--verbose "


rule verify_checksum:
    input:
        checksum=checksum_file,
        uploaded=upload_done,
    output:
        verified=touch(checksum_verified),
    params:
        remote_parent=remote_parent,
        remote_include=remote_include,
    shell:
        "rclone checksum sha256 "
        "{input.checksum} "
        "{params.remote_parent} "
        "--download "
        "--max-depth 1 "
        "--one-way "
        "--include '{params.remote_include}' "
        "--verbose "


rule target:
    default_target: True
    input:
        checksum=checksum_file,
        verified=checksum_verified,


onsuccess:
    with open(checksum_file, "rt") as f:
        sha256sum = f.read().strip().split()[0]
    print(f'{{"remote_path": "{remote_path}", "sha256sum": "{sha256sum}"}}', file=sys.stdout)
