You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
3.0 KiB

from argparse import ArgumentParser
from pathlib import Path
import toml
from openwrt_backup.retrieve import make_backup_on_remote, retrieve_backup_on_remote
from openwrt_backup.utils import (
client_from_config,
exec_remote,
get_new_backup_filepath,
)
from openwrt_backup.config import CONFIG_DATA # noqa
from openwrt_backup.prune import get_all_but_last_n
def do_prune(dest_path: Path, n: int, dry, hostname=None):
to_delete = get_all_but_last_n(dest_path, n, hostname)
for f in to_delete:
if dry:
print(f"Deleting: {f}")
else:
f.unlink()
def do_backup(
config_hostname,
ssh_config_root: Path,
backup_path: Path,
tmp_path: Path,
time_format,
dry,
):
client = client_from_config(config_hostname, ssh_config_root)
stdout, stderr = exec_remote(client, "echo $HOSTNAME")
hostname = stdout.read().decode().rstrip()
dest = get_new_backup_filepath(backup_path, time_format, hostname)
if dry:
print(f"Making backup {tmp_path / 'backup_latest.openwrt_backup.tar.gz'}")
print(
f"Copying remote {tmp_path / 'backup_latest.openwrt_backup.tar.gz'} to {dest}"
)
else:
backup_on_remote = make_backup_on_remote(client, tmp_path)
retrieve_backup_on_remote(client, backup_on_remote, dest)
return hostname
def main():
global CONFIG_DATA
parser = ArgumentParser()
parser.add_argument(
"-d",
"--dry",
action="store_true",
help="Don't do anything but show what would happen",
)
parser.add_argument(
"-c", "--config", help="config path for backup script", default=None
)
subparsers = parser.add_subparsers(dest="action", required=True)
p_run = subparsers.add_parser(
"run",
help=f"Make backup then prune all but the {CONFIG_DATA['backup']['keep']} most recent",
)
p_backup = subparsers.add_parser(
"backup", help="Same as run but do not delete any backups"
)
p_dump_config = subparsers.add_parser( # noqa
"dump-config", help="Show config and exit"
) # noqa
p_run.add_argument(
"name", help="Hostname in ssh_config file for openwrt device we need to backup"
)
p_backup.add_argument(
"name", help="Hostname in ssh_config file for openwrt device we need to backup"
)
args = parser.parse_args()
if args.config:
with open(args.config) as f:
CONFIG_DATA = toml.load(f)
if args.action == "dump-config":
print(toml.dumps(CONFIG_DATA))
exit(0)
hostname = do_backup(
args.name,
Path(CONFIG_DATA["ssh"]["root"]).expanduser(),
Path(CONFIG_DATA["backup"]["path"]).expanduser(),
Path(CONFIG_DATA["router"]["temp"]),
CONFIG_DATA["backup"]["time_format"],
args.dry,
)
if args.action != "backup":
do_prune(
Path(CONFIG_DATA["backup"]["path"]).expanduser(),
CONFIG_DATA["backup"]["keep"],
args.dry,
hostname,
)