#!/usr/libexec/platform-python -s
#  -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Module authors:
#   Björn Pedersen <bjoern.pedersen@frm2.tum.de>
#
# *****************************************************************************

"""Simple editor for the nicos keystore."""

import argparse
import getpass
import sys
from os import path

sys.path.insert(0, path.dirname(path.dirname(path.realpath(__file__))))

from nicos.utils.credentials.keystore import NicosKeyRing
from nicos.utils import config


class KeystoreTool:
    def __init__(self, storepass, path=None):
        self.keystore = NicosKeyRing(path)
        self.keystore.keyring_key = storepass

    def get(self, credid, domain='nicos'):
        print(self.keystore.get_password(domain, credid))

    def delpw(self, credid, domain='nicos'):
        self.keystore.delete_password(domain, credid)

    def put(self, credid, password, domain='nicos'):
        self.keystore.set_password(domain, credid, password)


def main():
    parser = argparse.ArgumentParser(prog='keystoreeditor')
    parser.add_argument(
        '--path', nargs='?', default=config.keystorepaths[-1],
        help='storage dir for the'
        ' keystore, default uses system default'
    )
    parser.add_argument('--storagepw', help='storage password')
    parser.add_argument('--password', help='password to store')
    parser.add_argument('op', choices=['get', 'add', 'del'], help='operation')
    parser.add_argument('credid', help='the credentials identifier')
    parser.add_argument(
        'domain', nargs='?', default='nicos', help='the storage domain'
    )

    opts = parser.parse_args(sys.argv[1:])

    if not opts.storagepw:
        opts.storagepw = getpass.getpass('storage password:')
    store = KeystoreTool(opts.storagepw, opts.path)
    try:
        if opts.op == 'get':
            store.get(opts.credid, opts.domain)
            return
        if opts.op == 'del':
            store.delpw(opts.credid, opts.domain)
            return
        if opts.op == 'add':
            if not opts.password:
                opts.password = getpass.getpass()
            store.put(opts.credid, opts.password, opts.domain)
            return
    except AssertionError:
        print("Error accessing the keystore", file=sys.stderr)


if __name__ == '__main__':
    main()
