| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- import argparse
- import sys
- from pathlib import Path
- from pc_backup.container import BorgmaticContainer, Configuration
- from pc_backup.keepass import KeePass
- from pc_backup.secret import Secret
- class CliArguments:
- @staticmethod
- def read_command(parser):
- args = parser.parse_args()
- if hasattr(args, "command"):
- return args.command(args)
- else:
- return parser.error("You should call at least one of the commands")
- @staticmethod
- def new() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(prog=sys.argv[0])
- subparsers = parser.add_subparsers()
- for sub in [
- CommandStart,
- CommandRm,
- CommandBash,
- CommandCreateRepo,
- CommandExportKey,
- CommandCreateSecrets,
- ]:
- p = subparsers.add_parser(sub.command, help=sub.help)
- sub.init_subparser(p)
- p.set_defaults(command=sub)
- return parser
- class Command:
- def __init__(self, namespace) -> None:
- for k, v in vars(namespace).items():
- if k != "type_":
- setattr(self, k, v)
- @classmethod
- def init_subparser(cls, p): ...
- class CommandStart(Command):
- command = "start"
- help = "start container"
- def run(
- self,
- *,
- container: BorgmaticContainer,
- config: Configuration,
- **kwargs,
- ):
- container.run(config)
- class CommandRm(Command):
- command = "rm"
- help = "remove container"
- def run(self, *, container: BorgmaticContainer, **kwargs):
- container.rm()
- class CommandBash(Command):
- command = "bash"
- help = "run shell in container"
- def run(self, *, container: BorgmaticContainer, **kwargs):
- container.exec(["bash"])
- class CommandCreateRepo(Command):
- command = "create_repo"
- help = "create repository"
- env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
- def run(self, *, container: BorgmaticContainer, **kwargs):
- container.exec(
- ["borgmatic", "repo-create", "--encryption", "repokey"], self.env_vars
- )
- class CommandExportKey(Command):
- command = "export_key"
- help = "export the repository key"
- env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
- def run(self, *, container: BorgmaticContainer, **kwargs):
- container.exec(["borgmatic", "export", "key"], self.env_vars)
- class CommandCreateSecrets(Command):
- command = "create_secrets"
- help = "create podman secrets"
- def run(self, *, secret_sources: list[Secret], **kwargs):
- keepass = KeePass.new(self.keepass_path)
- for s in secret_sources:
- s.create(keepass)
- @classmethod
- def init_subparser(cls, p):
- p.add_argument("keepass_path", type=Path, help="Path to the keepass")
|