#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import subprocess
import time
from mcrcon import MCRcon
from pathlib import Path


def exec_sync(src_dir="/mnt/src", dest_dir="/mnt/backup/daily_backup"):
    """
    src_dirをdest_dirにsync
    """
    src_dir = Path(src_dir)
    if not src_dir.exists():
        emsg = "not found {}".format(src_dir)
        raise ValueError(emsg)

    dest_dir = Path(dest_dir)
    root_dir = dest_dir.parent
    if not root_dir.exists():
        emsg = "not found {}".format(root_dir)
        raise ValueError(emsg)

    if not dest_dir.exists():
        dest_dir.mkdir()

    shell_cmd = [
        "rsync -a --delete",
        "{}/".format(src_dir),
        "{}/".format(dest_dir),
        "--exclude='logs'",
        "--exclude='spigot_server-*.jar'",
    ]
    res = subprocess.run(" ".join(shell_cmd), shell=True)
    res.check_returncode()


# connect
host = os.environ["RWA_RCON_HOST"]
port = os.environ["RWA_RCON_PORT"]
password = os.environ["RWA_RCON_PASSWORD"]
with MCRcon(host, password, int(port)) as mcr:

    msg = "The daily backup script has been launched,"
    mcr.command("say {}".format(msg))

    msg = "freezing the server for a short time."
    mcr.command("say {}".format(msg))

    # count down
    for i in range(4, 0, -1):
        time.sleep(1)
        msg = str(i)
        mcr.command("say {}".format(msg))

    # save
    mcr.command("save-all flush")

    # disable the server writing to the world files
    mcr.command("save-off")

    try:
        # backup data
        msg = "exporting data..."
        mcr.command("say {}".format(msg))
        exec_sync()

    except (ValueError, subprocess.CalledProcessError):
        msg = "somthing went wrong, please contact the system administrator."
        mcr.command("say {}".format(msg))

    else:
        msg = "done!"
        mcr.command("say {}".format(msg))

    finally:
        # enables the server writing to the world files
        mcr.command("save-on")
