#
# Copyright (C) 2018 Avencall
#
# 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/>


import os.path
import sys
import yaml
from uuid import uuid4

static_tokens_filename_with_path = '/etc/xivo-auth/conf.d/090-static-tokens.yml'
static_token_xc_acls = ['confd.users.read', 'confd.devices.*.update.read', 'confd.devices.*.read']


class ConfigFileExists(Exception):
    pass


class UnableToWriteConfigFile(Exception):
    pass


class UnableToReadConfigFile(Exception):
    pass


class UnableToExtractToken(Exception):
    pass


class StaticTokenManager(object):

    def __init__(self, conf_file_path):
        self.conf_file_path = conf_file_path

    def get_new_config(self):
        return dict(
            static_service_tokens=dict(
                xc=dict(
                    token=uuid4(),
                    acl=static_token_xc_acls)
            )
        )

    def write_config(self, config):
        if os.path.isfile(self.conf_file_path):
            raise ConfigFileExists

        try:
            with open(self.conf_file_path, 'w') as outfile:
                yaml.dump(config, outfile, default_flow_style=False)
                os.chmod(self.conf_file_path, 0o600)
        except IOError:
            raise UnableToWriteConfigFile

    def get_static_service_token(self):
        try:
            with open(self.conf_file_path, 'r') as conffile:
                cfg = yaml.unsafe_load(conffile)
            return cfg['static_service_tokens']['xc']['token']
        except IOError:
            raise UnableToReadConfigFile
        except:
            raise UnableToExtractToken

    def usage(self):
        print("Usage: %s [get|g|install|i]" % sys.argv[0])

    def main(self, argv):
        if len(argv) != 1:
            print("Not enough parameters, exiting")
            self.usage()
            sys.exit(1)

        task = argv[0]
        if (task == 'get') or (task == 'g'):
            try:
                print(self.get_static_service_token())
            except UnableToReadConfigFile:
                print("Unable to read file: %s" % self.conf_file_path)
                print("Does it exists with right owner and rights?")
                sys.exit(2)
            except UnableToExtractToken:
                print("Unable to extract token from config file %s" % self.conf_file_path)
                print("Please check or re-create the config file")
                sys.exit(5)

        elif (task == 'install') or (task == 'i'):
            try:
                self.write_config(self.get_new_config())
            except UnableToWriteConfigFile:
                print("Unable to write to file: %s" % self.conf_file_path)
                sys.exit(3)
            except ConfigFileExists:
                print("File %s exists, not overwriting" % self.conf_file_path)
                print("Please remove file and re-run")
                sys.exit(4)

        else:
            print("Unsupported argument: %s" % task)
            self.usage()
            sys.exit(2)


def main():
    manager = StaticTokenManager(static_tokens_filename_with_path)
    manager.main(sys.argv[1:])
