#!/usr/bin/python
# -*- coding: utf-8 -*-

" HMAC-OTP Software Token "

import os, sys, platform
import binascii
import hmac
from hashlib import sha1
import struct
from linotp.lib.crypt   import geturandom
from getopt import getopt, GetoptError
import time

import datetime

CONFIGFILE = "python-totp.cfg"
import ConfigParser, os
import urllib2
import random

class HmacOtp:
    def __init__(self, key, counter=0, digits=6):
        self.key = key
        self.counter = counter
        self.digits = digits

    def hmac(self, key=None, counter=None):
        key = key or self.key
        counter = counter or self.counter
        digest = hmac.new(key, struct.pack(">Q", counter), sha1)
        return digest.digest()

    def truncate(self, digest):
        offset = ord(digest[-1:]) & 0x0f

        binary  = (ord(digest[offset + 0]) & 0x7f) << 24
        binary |= (ord(digest[offset + 1]) & 0xff) << 16
        binary |= (ord(digest[offset + 2]) & 0xff) << 8
        binary |= (ord(digest[offset + 3]) & 0xff)

        return binary % (10 ** self.digits)

    def generate(self, key=None, counter=None):
        key = key or self.key
        counter = counter or self.counter
        otp = str(self.truncate(self.hmac(key, counter)))
        otp = (self.digits -len(otp))*"0"+otp
        self.counter = counter + 1
        return otp


def usage():
    print '''
    g, genkey: generate HMAC key
    o, offset: timeshift in seconds
    t, timestep: timestep
    a, add_offset: add seconds to offset
    u, url: the url for the LinOTP service. could be something like https://localhost/validate/check?user=USER&pass=PIN
            The OTP value will be appended to the URL
    c, check: if the otp value should be checked with the LinOTP server
    j, jitter: This is the maximum jitter, if the otp value is entered a bit before or after the middle of the given time interval
	r, range: calculate several OTP values around the current time. Number of timesteps
'''

def genkey():
    '''
    generate an hmac key an save it
    '''
    key = binascii.hexlify(geturandom(20))
    print "Your OTP Key:\n"
    print "    ", key
    print
    return key

def getpath():
    system=platform.system()
    config_path=None
    if system=="Linux":
        config_path = os.path.join(os.getenv("HOME"), ".%s" % CONFIGFILE)
    elif system=="Windows":
        config_path = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"), CONFIGFILE)
    else:
        print "I do not know your operating system"
        sys.exit(1)
    return config_path

def readconfig():
    '''
    Read and return the config object
    '''
    C = {}
    try:
        config = ConfigParser.SafeConfigParser()
        config.read(getpath())
        #print "CONFIG:" , config.items("TOTP")
        for (k,v) in config.items("TOTP"):
            C[k]=v
    except Exception as e:
        print ":: Error reading your configuration:"
        print ":: Please try to re-create a new configuration!"
        usage()
    return C

def saveconfig(param):
    '''
    save config object
    '''
    config = ConfigParser.SafeConfigParser()
    config.add_section('TOTP')
    for k,v in param.items():
        #print k, v
        config.set('TOTP', k, str(v))

    with open(getpath(), 'wb') as configfile:
        config.write(configfile)

def main():

    try:
        opts, args = getopt(sys.argv[1:], "hgt:o:a:cu:j:r:",
                ["help", "genkey", "timestep=", "offset=", "add_offset=", "check", "url=", "jitter=", "range="])

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



    CONFIG = readconfig()
    for opt, arg in opts:

        if opt in ('-h', '--help'):
            usage()
            sys.exit(0)
        elif opt in ('-g', '--genkey'):
            CONFIG['key'] = genkey()

        elif opt in ('-t', "--timestep"):
            CONFIG['timestep'] = int(arg)

        elif opt in ('-a', "--add_offset"):
            offset = int(CONFIG.get("offset",0)) + int(arg)
            CONFIG["offset"] = offset

        elif opt in ('-o', "--offset"):
            CONFIG['offset'] = int(arg)

        elif opt in ('-u', "--url"):
            CONFIG['url'] = arg

        elif opt in ('-j', "--jitter"):
            CONFIG['jitter'] = arg

        
    saveconfig(CONFIG)
    timestep = int(CONFIG.get('timestep',30))
    
    try:    

        binkey = binascii.a2b_hex( CONFIG['key'] )
        
        if CONFIG.get('jitter',0) != 0:
            jitter = random.randrange( - int(CONFIG.get('jitter')) , int(CONFIG.get('jitter')))
        else:
            jitter = 0

        T0 = time.time() + int(CONFIG.get('offset', 0)) + jitter
        counter = int((T0 / timestep)+0.5)
    
    except Exception as e:
        print "Error: Failed to initalize the token!: %s" % (str(e))
        sys.exit(1)
                
    otp = HmacOtp(binkey, counter=counter).generate()

    print "Your OTP with number %d is: %s" % (counter, otp)
    print "Happy Authenticating!"

    for opt, arg in opts:
        if opt in ('-c', '--check'):
            url = "%s%s" % (CONFIG.get("url"), otp)
            print "Requesting %s" % url
            f = urllib2.urlopen( url)
            print f.read()

        if opt in ('-r', '--range'):
            crange = int(arg)
            for i in range(counter - crange, counter + crange):
                otp = HmacOtp(binkey, counter=i).generate()
                nowDt       = datetime.datetime.fromtimestamp((i+0.5)*timestep / 1.0)
                print '%s : c:%s : otp %s' %(str(nowDt),str(i),str(otp))

if __name__ == '__main__':
    main()

