#!/usr/bin/python
# -*- coding: utf8 -*-

import urllib
import urllib2
import getpass
import re
import getopt
import sys
import time

def get_jira_resp(url, jsessionid):
    req = urllib2.Request(url)
    req.add_header("User-Agent", "LEGO-JIRA-changeloger/1.0.0")
    req.add_header("Cookie", "JSESSIONID=" + jsessionid)
    result = urllib2.urlopen(req)
    return result.read()

try:
    args = getopt.gnu_getopt(sys.argv[1:], 'u:p:o:')
except getopt.GetoptError:
    args = None

if not args or len(args[1]) == 0:
    print "Использование: jpya [-u имя_пользователя] [-p пароль] файл0=url0 [файл1=url1 [файлN=urlN]]"
    print "    имя_пользователя - имя пользователя в JIRA, если не указано, будет запрошено"
    print "    пароль           - пароль пользователя в JIRA, если не указан, будет запрошен"
    print "    файл=url         - jpya запишет в файл результат запроса по url"
else:
    j_username = j_password = None
    for arg in args[0]:
        if arg[0] == "-u":
            j_username = arg[1]
        elif arg[0] == "-p":
            j_password = arg[1]

    if not j_username:
        j_username = raw_input("Имя пользователя: ")
    if not j_password:
        j_password = getpass.getpass("Пароль: ", sys.stderr)

    cookieprocessor = urllib2.HTTPCookieProcessor()

    opener = urllib2.build_opener(urllib2.HTTPHandler, cookieprocessor)
    urllib2.install_opener(opener)

    req = urllib2.Request('https://jira.yandex-team.ru/login.jsp')
    req.add_data(urllib.urlencode({
        'os_username' : j_username,
        'os_password' : j_password,
        'os_destination' : '/secure/',
    }))

    connection = urllib2.urlopen(req)

    jsessionid = [x.value for x in cookieprocessor.cookiejar if x.name == 'JSESSIONID'][0]

    for arg in args[1]:
        url = re.search("=.*", arg).group(0)[1:]
        attempts_limit = 5
        attempts = 0
        fail = True
        while attempts < attempts_limit and fail is True:
            try:
                result = get_jira_resp(url, jsessionid)
                fail = False
            except urllib2.HTTPError, e:
                print "[%s] Ошибка получения XML. Попытка #%d, URL: %s" % (time.strftime("%Y.%m.%d %H:%M:%S"), attempts, url)
                print "Текст ошибки:"
                print e.read() + "\n"
                time.sleep(1)
            attempts += 1
        else:
            if fail is True:
                print "Ошибка получения XML. Всего %d попыток, URL: %s" % (attempts_limit, url)
            else:
                f = open(re.search("[^=]*=", arg).group(0)[:-1], "w")
                f.write(get_jira_resp(re.search("=.*", arg).group(0)[1:], jsessionid))
                f.close()

