#!/usr/bin/env python
# vim:ts=4:sw=4:expandtab

# 
# Copyright (C) 2009 Red Hat, Inc.
#
# This file is part of IcedTea.
#
# IcedTea 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, version 2.
#
# IcedTea 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 IcedTea; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA.
#
# Linking this library statically or dynamically with other modules is
# making a combined work based on this library.  Thus, the terms and
# conditions of the GNU General Public License cover the whole
# combination.
#
# As a special exception, the copyright holders of this library give you
# permission to link this library with independent modules to produce an
# executable, regardless of the license terms of these independent
# modules, and to copy and distribute the resulting executable under
# terms of your choice, provided that you also meet, for each linked
# independent module, the terms and conditions of the license of that
# module.  An independent module is a module which is not derived from
# or based on this library.  If you modify this library, you may extend
# this exception to your version of the library, but you are not
# obligated to do so.  If you do not wish to do so, delete this
# exception statement from your version.
#


import os
import sys
import re
import datetime
import urllib
import subprocess

def download_url(url, as_file):
    """
    Download the file from the url to the disk
    """
    web_file = urllib.urlopen(url)
    contents = ''
    for line in web_file.readlines():
        if '404 not found' in line.lower() :
            raise IOError('file not found: ' + url)
        elif 'not found on this server'  in  line.lower():
            raise IOError('file not found: ' + url)
        if (len(contents) > 0):
            contents = contents
        contents = contents + line
    local_file = open(as_file, 'w')
    local_file.write(contents)
    web_file.close()
    local_file.close()
    #print 'downloaded file ' + url 
    #print 'saved it as ' + local_file_name


def get_changeset_from_icedtea_version(version_file):
    """
    Returns a mercurial changeset string based on the information contained
    in the output of java -version as contained in version_file
    """

    ver_file = open(version_file, 'r')
    # discard first line
    line = ver_file.readline()

    line = ver_file.readline().strip()
    #regexp = re.compile(r'.*\(IcedTea[67]? [0-9]+\.[0-9]+(?:pre-)?-r([0-9a-f]+)\).*')
    regexp = re.compile(r'.*\(IcedTea[67]?.*(pre-)?-r([0-9a-f]+)\).*')
    match = regexp.match(line)
    if match:
        return str(match.group(2))
    else:
        raise IOError('No revision found')

    ver_file.close() 


def email_jtreg_results(project, date, old_date, hg_dir):
    """
    email jtreg results for a project

    where a project is one of openjdk[67] or icedtea[67]
    """
    # download version files for both versions
    download_url(base_url + str(old_date) + '/' + project + '_version', 
        project + '_version-' + str(old_date))
    download_url(base_url + str(date) + '/' + project + '_version', 
        project + '_version-' + str(date))

    old_changeset = get_changeset_from_icedtea_version(project + '_version-' + str(old_date))
    new_changeset = get_changeset_from_icedtea_version(project + '_version-' + str(date))

    jtreg_tests = ['hotspot', 'langtools', 'jdk']    
    for jtreg_test in jtreg_tests:
        # download test files for both versions
        download_url(base_url + str(date) + '/' + project + '_jtreg_output-' + jtreg_test, 
            project + '_jtreg_output-' + jtreg_test + '-' + str(date))
        download_url(base_url + str(old_date) + '/' + project + '_jtreg_output-' + jtreg_test,
            project + '_jtreg_output-' + jtreg_test + '-' + str(old_date))
    
        subprocess.call([
            './jtreg-diff-emailer.py',                                      # script
            project,                                                        # project name
            jtreg_test,                                                     # test suite
            project + '_jtreg_output-' + jtreg_test + '-' + str(old_date),  # old output file
            project + '_jtreg_output-' + jtreg_test + '-' + str(date),      # new output file
            project + '_version-' + str(old_date),                          # old version file
            project + '_version-' + str(date),                              # new version file
            hg_dir,                                                         # hg dir
            old_changeset,                                                  # old changeset
            new_changeset                                                   # new changeset
            ])


def email_mauve_results(project, date, old_date, hg_dir):
    """
    Email if there are regressions in the mauve test suite for a project

    project is one of openjdk[67] or icedtea[67]
    """
    download_url(base_url + str(old_date) + '/' + project + '_version', 
        project + '_version-' + str(old_date))
    download_url(base_url + str(date) + '/' + project + '_version', 
        project + '_version-' + str(date))

    old_changeset = get_changeset_from_icedtea_version(project + '_version-' + str(old_date))
    new_changeset = get_changeset_from_icedtea_version(project + '_version-' + str(date))

    download_url(base_url + str(date) + '/' + project + '_mauve_output', 
        project + '_mauve_output-' + str(date))
    download_url(base_url + str(old_date) + '/' + project + '_mauve_output', 
        project + '_mauve_output-' + str(old_date))
    subprocess.call([
        './mauve-diff-emailer.py',                      # script
        project,                                        # project name
        project + '_mauve_output-' + str(old_date),     # old output file
        project + '_mauve_output-' + str(date),         # new output file
        project + '_version-' + str(old_date),          # old version file
        project + '_version-' + str(date),              # new version file
        hg_dir,                                         # hg dir
        old_changeset,                                  # old changeset
        new_changeset                                   # new changeset
        ])



def main(args):
    """
    Download test reports from icedtea.classpath.org, and look for changes. 
    Send email to authors if there are any changes.
    """

    num_days = 1

    # this script runs after midnight, so use yesterday's results
    date = datetime.date.today() - datetime.timedelta(days=1)
    #date = datetime.date.today() - datetime.timedelta(days=3)
    old_date = date - datetime.timedelta(days=num_days)

    # icedtea6 mauve
    email_mauve_results('icedtea6', date, old_date, '../icedtea6-rebuild')
    # icedtea6 jtreg
    email_jtreg_results('icedtea6', date, old_date, '../icedtea6-rebuild')
    # icedtea7 jtreg
    email_jtreg_results('icedtea7', date, old_date, '../icedtea')


# globals
base_url = 'http://icedtea.classpath.org/~omajid/logs/'


if __name__ == '__main__':
    main(sys.argv)

