#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2023 fx-kirin <fx.kirin@gmail.com>
#
# Distributed under terms of the MIT license.

"""

"""
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2022 fx-kirin <fx.kirin@gmail.com>
#
# Distributed under terms of the MIT license.

__ALL__ = ["update", "init"]

import logging
import os
from pathlib import Path

import delegator
import fire
import kanilog


import kanilog

logger = kanilog.get_module_logger(__file__, 1)


def update(commit_message=None, filepath=None):
    result = delegator.run(f"crontab {filepath}").out
    if len(result.strip()) > 0:
        logger.warning(result)
        logger.warning("Cron-update failed.")
        return
    if filepath is None:
        filepath = "%s.crontab" % os.environ["USER"]
    result = delegator.run(f"git status {filepath} 2> /dev/null").out
    last_line = result.split('\n')[-2]
    if "nothing" not in last_line or "untracked" in last_line:
        result = delegator.run(f"git add {filepath} 2> /dev/null").out
        if commit_message is None:
            result = delegator.run("git commit -m \"Automatical upadte by crongit.\" 2> /dev/null").out
        else:
            result = delegator.run(f"git commit -m \"{commit_message}\" {filepath} 2> /dev/null").out
        logger.info("Automatically update crontab and commit your cron file.")
        return


def init(filepath=None):
    if filepath is None:
        filepath = "%s.crontab" % os.environ["USER"]
    result = delegator.run("crontab -l 2> /dev/null").out
    Path(filepath).write_text(result)
    logger.info("Write crontab file from the file that currently set.")


def status():
    result = delegator.run("crontab -l").out
    print(result)


if __name__ == "__main__":
    kanilog.setup_logger(
        logfile="/tmp/%s.log" % (Path(__file__).name), level=logging.INFO
    )
    fire.Fire({"update": update, "init": init})
