#!/usr/bin/env python
# encoding: utf-8
"""
@author: chenhao
@file: tmp.py
@time: 2022/8/8 18:30
"""
import os
import click

SERVER_MAP = {
    "hz4090": ("117.50.179.140", "1022", "root", "/home/bmm-system/data/chenhao"),
    "prod": ("jumpserver.zphz.cn", "2222", "JMS-6611c264-4a45-4011-ae1a-a5b19cd65fb5", "/DATA/disk1/chenhao"),
    "deploy": ("jumpserver.zphz.cn", "2222", "JMS-e2be0448-d5bb-448f-9406-72feeb2641d8", "/data/chenhao"),
}

src_home = "/Users/chenhao"


@click.command()
@click.option('--machine_name', '-m', help='目标机器')
@click.option('--dst_path', '-d', help='dst path')
@click.option('--current', '-c', is_flag=True, default=False, help='whether download to current dir')
@click.argument('src_path')
def download(src_path: str, machine_name: str, dst_path=None, current=True):
    """
    download src_path from remote server to dst_path
    if dst_path is not None, download to dst_path
    if --current is set, download to current dir
    else download to the same dir as src_path, just replace the home dir
    """
    ip, port, user, home = SERVER_MAP[machine_name]
    if isinstance(home, str):
        home = [home]

    file_name = os.path.basename(os.path.normpath(src_path))

    if not dst_path:
        if current:
            cwd = os.getcwd()
            dst_path = os.path.join(cwd, file_name)
        else:
            for h in home:
                dst_path = src_path.replace(h, src_home)

    dst_dir_path = os.path.dirname(dst_path)
    print(dst_dir_path)
    os.makedirs(dst_dir_path, exist_ok=True)
    cmd = f"rsync  -avz --progress -e 'ssh {'-p '+port if port else ''}' {user}@{ip}:{src_path} {dst_path}"

    click.echo(cmd)
    os.system(cmd)


if __name__ == "__main__":
    download()
