#!/usr/bin/python

# log into bugzilla and write bugz cookie file

import sys, os


def update_bugz_cookie(cookie):
    """overwrites ~/.bugz_cookie file with bugzilla cookie in LWP format"""
    jar = os.path.expanduser('~/.bugz_cookie')
    jarfd = open(jar, 'w')
    os.chmod(jar, 0600)
    jarfd.write("""#LWP-Cookies-1.0

Set-Cookie3: IPCZQX018ef15359=%s; path="/"; domain=.novell.com; expires="2010-10-10 12:34:56"
""" % cookie.split()[2])
    jarfd.close()


def get_cookie():
    import httplib
    import getpass
    from urllib import urlencode
    from urlparse import urlparse, urljoin
    import os

    usernamefile = os.path.expanduser('~/.bzuser')
    if os.path.isfile(usernamefile):
        username = open(usernamefile).readlines()[0]
    else:
        username = getpass.getuser()
    print >>sys.stderr, 'Password: ',
    password = getpass.getpass(prompt='')
    url_base, url_rel = 'https://bugzilla.novell.com', '/ICSLogin/'
    target_url = 'https://bugzilla.novell.com/ichainlogin.cgi?target=index.cgi'

    params = {'url': target_url,
          'context': 'default',
          'message': 'Please log In',
          'proxypath': 'reverse',
          'username': username, 
          'password': password,
          }
    data = urlencode(params)

    host = urlparse(url_base)[1]
    #host = 'aust.suse.de'

    h = httplib.HTTPS(host)
    #h.set_debuglevel(1)
    h.putrequest('POST', url_rel)
    h.putheader('User-agent', 'python-httplib 1.0')
    h.putheader('Host', host)
    h.putheader('Content-Length', str(len(data)))
    h.putheader('Content-Type', 'application/x-www-form-urlencoded')
    h.endheaders()

    h.send(data)

    errcode, errmsg, headers = h.getreply()
    #print >>sys.stderr, 'errcode: ', errcode
    #print >>sys.stderr, 'headers: ', headers
    #h.close()

    if errcode == 302:
        if not headers.has_key('set-cookie'):
            print >>sys.stderr, 'no cookie received...'
            return None
        else:
            c = headers['set-cookie']
            c = c.split('; ')

            cookie = '\t'.join([urljoin(url_base, url_rel),
                        c[0].split('=')[0],
                        c[0].split('=')[1],
                        '1877472000',
                        c[2].split('=')[1],
                        c[1].split('=')[1],
                        '9',
                        '0',
                       ])

            return cookie
            

    else:
        print >>sys.stderr, 'could not log in'
        print >>sys.stderr, errcode
        print >>sys.stderr, errmsg
        print >>sys.stderr, headers
        if headers: print >>sys.stderr, headers.has_key('set-cookie')
        return None


if __name__ == '__main__':
    cookie = get_cookie()

    if not cookie:
        sys.exit(1)
    else:
        update_bugz_cookie(cookie)
        sys.exit(0)

