#!/usr/bin/env python3
# pylint: disable=invalid-name

"""Runs rclone securely to download the Keepass password database from
Nextcloud.

This is meant as a bootstrap step to get the Keepass password database
so that other steps that depend on the database can be used.
"""

import getpass
import os
import os.path
import subprocess  # nosec


DB_PATH = "Documents/Database.kdbx"
DEST = os.path.expanduser(f"~/{ os.path.dirname(DB_PATH) }")
SOURCE = f"nextcloud:{DB_PATH}"


if __name__ == "__main__":
    username = input(f"Enter username (defaults to {getpass.getuser()}): ")
    if not username:
        username = getpass.getuser()
    password = getpass.getpass("Enter password (will not echo): ")
    obscured_password = subprocess.run(  # nosec
        ["rclone", "obscure", "-"],
        input=password,
        capture_output=True,
        check=True,
        text=True,
    ).stdout.strip()
    os.execvp(  # nosec
        "rclone",
        [
            "rclone",
            "copy",
            "--webdav-pass",
            obscured_password,
            "--webdav-user",
            username,
            SOURCE,
            DEST,
        ],
    )
