#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#  privacyIDEA
#  2015-03-16 Cornelius Kölbel, <cornelius@privacyidea.org>
#             initial writeup to fetch offline auth_items
#
#  (c) 2015 Cornelius Kölbel, cornelius@privacyidea.org
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# License as published by the Free Software Foundation; either
# version 3 of the License, or any later version.
#
# This code 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/>.
#
"""
This tool is used to fetch the offline authentication items for the given
user on this machine.
"""
import getpass
from privacyideautils.clientutils import *
import socket
import sys
import argparse
from privacyideautils.offline import save_auth_item

VERSION = '2.2'
DESCRIPTION = __doc__


def create_arguments():
    parser = argparse.ArgumentParser(description=DESCRIPTION,
                                     fromfile_prefix_chars='@')
    parser.add_argument("-U", "--url",
                        help="The URL of the privacyIDEA server including "
                        "protocol and port like "
                        "https://localhost:5001",
                        required=True)
    parser.add_argument("-a", "--admin",
                        help="The name of the administrator like "
                        "admin@admin or admin",
                        required=True)
    parser.add_argument("-r", "--adminrealm",
                        help="The realm of the administrator like "
                        "'admin'",
                        default="")
    parser.add_argument("-p", "--password",
                        help="The password of the administrator. Please "
                        "avoid to post the password at the command line. "
                        "You will be asked for it - or you can provide the "
                        "password in a configuration file. "
                        "Note, that you can write a file password.txt "
                        "containing two lines '--password' and the second "
                        "line the password itself and add this to the "
                        "command line with @password.txt")
    parser.add_argument("-v", "--version",
                        help="Print the version of the program.",
                        action='version', version='%(prog)s ' + VERSION)
    parser.add_argument("--nosslcheck",
                        help="Do not check SSL certificates.",
                        action="store_true")
    parser.add_argument("--sqlfile",
                        help="The SQLite file where the offline information "
                             "is to be stored.")
    args = parser.parse_args()
    return args




def main():
    args = create_arguments()

    if not args.password:
        password = getpass.getpass(prompt="Please enter password for"
                                   " '%s':" % args.admin)
    else:
        password = args.password

    sqlfile = args.sqlfile or "offlineotp.sqlite"

    # Create the privacyideaclient instance
    client = privacyideaclient(args.admin, password, args.url,
                               no_ssl_check=args.nosslcheck)

    name = socket.gethostname()

    params = {"hostname": name}

    response = client.get("/machine/authitem/offline", params)
    result = response.data.get("result")

    if result.get("status"):
        machinetokens = result.get("value").get("offline", {})
        if len(machinetokens) == 0:
            # No token available
            raise Exception("No token found for the application on this machine!")
        else:
            for authitem in machinetokens:
                """
                machinetokens is a list of offline applications (
                dictionaries) for this machine. It contains the following keys:
                * count
                * response (dict of hashes with counter as kex)
                * user - the assigned user in the machine token
                * username - the owner of the token
                """
                print("number of hashes: %s" % authitem.get("count"))
                print("local user: %s" % authitem.get("user"))
                print("token owner: %s" % authitem.get("username"))
                #print "hashes: %s" % authitem.get("response")
                save_auth_item(sqlfile, authitem)
    else:
        # False status
        print(result.get("error").get("message"))


if __name__ == '__main__':
    try:
        main()
    except Exception as ex:
        print("Error: %s" % ex)
        sys.exit(5)
