#!/usr/bin/python
'''

  product:  LinOTP2
  module:   Admin Client
  tool:     setpins.py
  edition:  Enterprise Edition
  
  Copyright (C) 2010 - 2013 LSE Leading Security Experts GmbH
  License:  LSE
  contact:  http://www.linotp.org
            http://www.lsexperts.de
            linotp@lsexperts.de

  Description:  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()
