#!/usr/bin/python3
#
#   Debian Changes Bot
#   Copyright (C) 2016-2020 Sebastian Ramacher <sramacher@debian.org>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as
#   published by the Free Software Foundation, either version 3 of the
#   License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

import datetime
import shutil
import sys
import syslog
import tempfile
from pathlib import Path


TARGET_DIR = Path("/var/lib/debian-devel-changes-bot/inject")


def main():
    syslog.openlog("ddc-bot-inject")
    try:
        TARGET_DIR.mkdir(exist_ok=True)
    except Exception as e:
        syslog.syslog("Target directory does not exist: {e}")
        return 75

    out_name = None
    try:
        with tempfile.NamedTemporaryFile(
            prefix="{}-".format(datetime.datetime.now(datetime.UTC).isoformat()),
            delete=False,
        ) as out:
            out_name = Path(out.name)
            with open("/dev/stdin", mode="rb") as stdin:
                shutil.copyfileobj(stdin, out)
    except Exception as e:
        syslog.syslog(syslog.LOG_ERR, f"Failed to copy mail: {e}")
        if out_name is not None:
            out_name.unlink()
        return 75

    try:
        shutil.move(out_name, TARGET_DIR)
    except Exception as e:
        syslog.syslog(syslog.LOG_ERR, f"Failed to move mail: {e}")
        out_name.unlink()
        return 75

    return 0


if __name__ == "__main__":
    sys.exit(main())
