import os
import sys
from subprocess import check_call
from tempfile import NamedTemporaryFile


TEMPLATE = (
    "# m h  dom mon dow   command\n\n"
    "*/{cron_interval_writedata}  *  *  *  * {py3} -m solthermpi writedata"
    " >> {cron_logpath}/`date +\%Y\%m\%d`.log 2>&1\n"

    "*/{cron_interval_senddata} *  *  *  * {py3} -m solthermpi senddata"
    " >> {cron_logpath}/`date +\%Y\%m\%d`.log 2>&1\n"

    "0    *  *  *  * {py3} -m solthermpi update"
    " >> {cron_logpath}/`date +\%Y\%m\%d`.log 2>&1\n"

    "0    *  *  *  * {py3} -m solthermpi sendcronlog\n"

    "*/5  *  *  *  * {py3} -m solthermpi resetusb"
    " >> {cron_logpath}/`date +\%Y\%m\%d`.log 2>&1\n"

    "*/2  *  *  *  * {py3} -m solthermpi rebootif"
    " >> {cron_logpath}/`date +\%Y\%m\%d`.log 2>&1\n"

    "0    0  *  *  * {py3} -m solthermpi reboot"
    " >> {cron_logpath}/`date +\%Y\%m\%d`.log 2>&1\n"
)


def update_crontab(config):
    """
    Install a new crontab (only if we're on a Raspberry Pi device)

    Args:
        config: configparser.ConfigParser object
    """
    interval_write = config.getint("GENERAL", "cron_interval_writedata")
    interval_send = config.getint("GENERAL", "cron_interval_senddata")
    cron_logpath = config.get("GENERAL", "cron_logpath")
    # path to current python interpreter
    py3 = sys.executable

    crontab = TEMPLATE.format(cron_interval_writedata=interval_write,
                              cron_interval_senddata=interval_send,
                              cron_logpath=cron_logpath, py3=py3)

    if "/home/pi" in os.path.expanduser("~"):
        with NamedTemporaryFile(mode='w+b', delete=False) as f:
            f.write(crontab.encode("utf-8"))
        check_call(["crontab", f.name])
        os.remove(f.name)
        print("Installed new crontab")
    else:
        print(crontab)
