#!/usr/bin/python

# Unix SMB/CIFS implementation.
# Copyright (C) Kamen Mazdrashki <kamen.mazdrashki@postpath.com> 2009
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#

"""DRS prefixMap helpers"""

import ber_oid

def make_attid(oid):
    # get last sub-identifier
    lastValue = int(oid.split('.').pop())
    #make binary-oid
    binaryOID = ber_oid.encode(oid)
    
    if lastValue < 128:
        oidPrefix = binaryOID[:-2]
    else:
        oidPrefix = binaryOID[:-4]

    lowerWord = lastValue % 16384
    if lastValue >= 16384:
        # mark it so that it is known to not be the whole lastValue
        lowerWord = lowerWord + 32768
    
    upperWord = 'prefixIndex'
    attid = '%04X' % lowerWord
    
    return (oidPrefix, attid)


def oid_from_attid(bin_prefix, attid):
    # separate the ATTRTYP into two parts
    if attid.startswith('0x'):
        attid = attid[2:]
    attid = ('00000000' + attid)[-8:]
    hi_word = attid[:4]
    lo_word = attid[4:]

    val = int(lo_word, 16)
    if val < 128:
        bin_oid = bin_prefix + lo_word[-2:]
    else:
        if val >= 32768:
            val -= 32768
        tmp = ((val / 128) % 128) + 128
        tmp = '%02X' % tmp
        tmp = tmp[-2:]
        bin_oid = bin_prefix + tmp
        tmp = val % 128
        tmp = '%02X' % tmp
        tmp = tmp[-2:]
        bin_oid = bin_oid + tmp
    
    print "bin_oid: %s" % bin_oid
    return ber_oid.decode(bin_oid)
