#!/usr/bin/python3

# Copyright (C) 2019-2020
#
# * Felix Delattre <felix@delattre.de>
# * W. Martin Borgert <debacle@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 configparser
import sys


class Configuration(object):
    """Configuration object, created from configuration ini file"""

    def __init__(self, configfile, version):

        self.version = version
        config = configparser.RawConfigParser()
        config.read(configfile)

        if config.has_section("XMPP") == config.has_section("Email"):
            print(
                "Error: Either XMPP or Email must be configured, but not both!", file=sys.stderr
            )
            raise ValueError

        if config.has_section("XMPP"):
            xmpp = config["XMPP"]
            self.target_gateway = "xmpp"
            self.xmpp_recipient_jids = (xmpp.get("recipient_jids") or "").split()
            self.xmpp_sender_jids = (xmpp.get("sender_jids") or "").split()
            self.xmpp_component_jid = xmpp.get("component_jid") or "sms4you.localhost"
            with open(
                xmpp.get("component_password_file") or "/etc/sms4you/xmpp_component_password"
            ) as f:
                self.xmpp_component_password = f.read().strip()
            self.xmpp_server = xmpp.get("server") or "localhost"
            self.xmpp_server_port = xmpp.get("port") or "5347"
        elif config.has_section("Email"):
            email = config["Email"]
            self.target_gateway = "email"
            self.email_username = email.get("email_username") or ""
            self.email_password = email.get("email_password") or ""
            self.email_smtp_host = email.get("smtp_host") or ""
            self.email_smtp_port = email.getint("smtp_port") or 465
            self.email_imap_host = email.get("imap_host") or ""
            self.email_imap_port = email.getint("imap_port") or 993
            self.recipient_emails = (email.get("recipient_emails") or "").split()
            self.sender_emails = (email.get("sender_emails") or "").split()

        if config.has_section("Modem"):
            modem = config["Modem"]
            self.modem_filter = modem.get("filter") or ""
            with open(modem.get("sim_pin_file") or "/etc/sms4you/sim_pin") as f:
                self.modem_sim_pin = f.read().strip()
