#!/usr/bin/env python3
import os
import time
from pathlib import Path

# go to script directory
os.chdir(os.path.dirname(os.path.abspath(__file__)))


def boxkind():
    sysclass = []
    for kind in 'ionopi', 'ionopimax':
        if Path(f'/sys/class/{kind}').exists():
            sysclass.append(kind)
    if len(sysclass) > 1:
        raise RuntimeError(f'box kind not unique: {sysclass}') 
    return sysclass[0] if sysclass else 'rpi'

HOST = "l_samenv@linse-c"
SUBDIR = f"boxes/{boxkind()}_images"
DEFDEST = f"{HOST}:{SUBDIR}"
file = f"{time.strftime('%Y-%m-%d')}.lz4"


def prt(text):
    print(time.strftime('%H:%M:%S'), text)


dest = input(f"destination directory for image [{DEFDEST}]: ") or DEFDEST


host, _, subdir = dest.partition(':')
if not subdir:
    if '@' in host:
        subdir = SUBDIR
    else:
        subdir, host = host, HOST

if os.system(f'ssh {host} cd {subdir}'):
    raise ValueError(f'{host}:{subdir} does not exist')
if not os.system(f"bash -c 'ssh {host} ls {subdir}/{file} &> /dev/null'"):
    print(f'{host}:{subdir}/{file} already exists')

file = input(f"destination file name [{file}]: ") or file

prt('needs about 10 minutes')

pid = os.getpid()
tmpfile = f"/media/rpi{pid}.img"
os.system(f"sudo bash image-backup -i {tmpfile}")
prt('pack and copy ... (3 minutes)')
os.system(f"bash -c 'dd if={tmpfile} bs=512k | lz4 | ssh {host} dd of={subdir}/{file} bs=512k'")
prt('cleanup ...')
os.system(f"sudo rm -f {tmpfile}")
