#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# update_action.py
#
# Copyright (C) 2021-2022 Franco Masotti (franco \D\o\T masotti {-A-T-} tutanota \D\o\T com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
r"""update_action.py."""

import shlex
import sys

import fpyutils
import yaml


def send_notification(message: str, notify: dict):
    m = notify['gotify']['message'] + '\n' + message
    if notify['gotify']['enabled']:
        fpyutils.notify.send_gotify_message(notify['gotify']['url'],
                                            notify['gotify']['token'], m,
                                            notify['gotify']['title'],
                                            notify['gotify']['priority'])
    if notify['email']['enabled']:
        fpyutils.notify.send_email(
            message, notify['email']['smtp_server'], notify['email']['port'],
            notify['email']['sender'], notify['email']['user'],
            notify['email']['password'], notify['email']['receiver'],
            notify['email']['subject'])


if __name__ == '__main__':

    def main():
        configuration_file = shlex.quote(sys.argv[1])
        config = yaml.load(open(configuration_file, 'r'),
                           Loader=yaml.SafeLoader)

        # Action types. Preserve this order.
        types = ['pre', 'update', 'post']
        services = config['services']

        for service in services:
            for type in types:
                for cmd in services[service]['commands'][type]:
                    for name in cmd:
                        retval = fpyutils.shell.execute_command_live_output(
                            cmd[name]['command'], dry_run=False)
                        if cmd[name]['notify']['success'] and retval == cmd[
                                name]['expected_retval']:
                            send_notification(
                                'command "' + name + '" of service "' +
                                service + '": OK', config['notify'])
                        elif cmd[name]['notify']['error'] and retval != cmd[
                                name]['expected_retval']:
                            send_notification(
                                'command "' + name + '" of service "' +
                                service + '": ERROR', config['notify'])

    main()
