#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#    LinOTP - the open source solution for two factor authentication
#    Copyright (C) 2010 - 2014 LSE Leading Security Experts GmbH
#
#    This file is part of LinOTP server.
#
#    This program is free software: you can redistribute it and/or
#    modify it under the terms of the GNU Affero General Public
#    License, version 3, as published by the Free Software Foundation.
#
#    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/>.
#
#
#    E-mail: linotp@lsexperts.de
#    Contact: www.linotp.org
#    Support: www.lsexperts.de
#
""" This tool is used to set pins for tokens
                massively.
                It takes a file with the contents
                <serial>:<pin>
                with no blanks!

  Dependencies: clientutils,

"""

VERSION = '0.1'
import os
from getopt import getopt, GetoptError
import getpass
from linotputils.clientutils import *
import pprint


import ldap
import sys
from hashlib import sha1
import hmac, struct, binascii
import string


if sys.version_info[0:2] >= (2, 6):
    from json import loads
else:
    from simplejson import loads
import logging

def usage():
    print  '''

    --linotp2=linotp2url
    --admin=linotp2 admin
        Password is asked
    --filename=<filename>

'''


def main():
    linotp_url = ""
    linotp_protocol = ""
    admin = ""
    adminpw = ""
    filename = ""


    try:
        opts, args = getopt(sys.argv[1:], "",
                ["help", "linotp2=", "admin=", "filename="])

    except GetoptError:
        print "There is an error in your parameter syntax:"
        usage()
        sys.exit(1)


    for opt, arg in opts:
        if opt in ('--help'):
            usage()
            sys.exit(0)
        elif opt in ('--linotp2'):
            if arg.startswith('https://'):
                linotp_protocol = "https"
                linotp_url = arg[8:]
            elif arg.startswith('http://'):
                linotp_protocol = "http"
                linotp_url = arg[7:]
            else:
                print "Malformed url format. You need to start with http or https [" + arg + "]"
                sys.exit(1)
        elif opt in ('--admin'):
            admin = arg
            adminpw = getpass.getpass(prompt="Please enter password for '%s':" % admin)
        elif opt in ('--filename'):
            filename = arg



    # Create the linotpclient instance
    print "LinOTP 2 protocol: %s " % linotp_protocol
    print "LinOTP 2 server  : %s " % linotp_url
    lotpc = linotpclient(linotp_protocol, linotp_url, admin=admin, adminpw=adminpw)

    # setting pins

    print "reading file %s" % filename
    f = open(filename, 'r')
    for line in f:
        (serial, pin) = line.split(':', 1)
        pin = string.rstrip(pin)
        pin = string.rstrip(pin, '\n')
        print "setting pin of >>%s<< to >>%s<<" % (serial, pin)
        r1 = lotpc.set({'serial' : serial, 'pin' : pin })
        print "    ", r1
    f.close



if __name__ == '__main__':
    main()
