#!/usr/bin/python

import os, os.path, re, glob, stat, string, cgi
from color import *
from ConfigParser import ConfigParser

DESCRIPTIONS_DIR = '../db/download-descriptions'

print("Content-Type: text/html\n")

arch = plat = None

## Parse arguments ###########################################################

args = cgi.FieldStorage()

if args.has_key( 'type' ):
    dltype = args['type'].value
else:
    dltype = 'nightly'

if args.has_key( 'lang' ):
    language = args['lang'].value
else:
    language = 'en'

if args.has_key( 'arch' ):
    arch = args['arch'].value

if args.has_key( 'platform' ):
    plat = args['platform'].value

## Configuration #############################################################
## Colors
#

if dltype == "nightly":
    colorTH      = Color( 0xFF, 0xE0, 0xA0 )  # Table headers
elif dltype == "nightly2":
    colorTH      = Color( 0x91, 0xAB, 0xC6 )  # Table headers
elif dltype == "snapshots":
    colorTH      = Color( 0xA0, 0xE0, 0xFF )  # Table headers
elif dltype == "snapshots2":
    colorTH      = Color( 0xA0, 0xE0, 0xFF )  # Table headers

colorBG      = Color( 0xEE, 0xEE, 0xEE )  # Background of page
colorTD      = colorBG                    # Table cells
colorFileDL  = Color( 0x99, 0xDD, 0x99 )  # File download available cell
colorFileNA  = Color( 0xDC, 0x99, 0x99 )  # File download not available cell
colorFrame   = Color( 0x00, 0x00, 0x00 )  # Table separator lines
colorGhosted = Color( 0x99, 0x77, 0x77 )  # File download not available text

## Package descriptions and other strings
#
descriptions = ConfigParser()
if not os.path.exists( os.path.join( DESCRIPTIONS_DIR, language + '.txt' ) ):
    language = 'en'
descriptions.read( [ os.path.join( DESCRIPTIONS_DIR, 'en' ),
    os.path.join( DESCRIPTIONS_DIR, language + '.txt' ) ] )

## Get size units
#
byteUnit = descriptions.get( 'units', 'byte-unit', '' )
kilobyteUnit = descriptions.get( 'units', 'kilobyte-unit', '' )
megabyteUnit = descriptions.get( 'units', 'megabyte-unit', '' )
gigabyteUnit = descriptions.get( 'units', 'gigabyte-unit', '' )
units = ( byteUnit, kilobyteUnit, megabyteUnit, gigabyteUnit )

root  = '../downloads/' + dltype

## Functions #################################################################

def formatSize( size ):
    size  = float( size )

    for unit in units:
        if size <= 1000:
           return '%.2f %s' % (size, unit )
        else:
           size = size / 1000

## Process files #############################################################

oldcwd = os.getcwd()
os.chdir( root )
dates = glob.glob( '[0-9]*' )
dates.sort()
dates.reverse()
os.chdir( oldcwd )

groups = {}

for date in dates:
    for group in os.listdir( os.path.join( root, date ) ):
        # Is this file a directory? If it is, then it means
        # this file's name is the name of a group, except if it's named
        # "logs", in which case we don't consider it.
        if group != 'logs' and stat.S_ISDIR( os.stat( os.path.join( root, date, group ) )[0] ):
            if not groups.has_key( group ):
                groups[group] = {}

            for package in os.listdir( os.path.join( root, date, group ) ):
                # Skip MD5 checksum files.
                if package[-4:] == '.md5': continue

                if package[-4:] == '.php':
                    package = package[14:][:-4]
                elif package[-8:] == '.tar.bz2':
                    # Remove the 'AROS-YYYYMMDD-' prefix and '.tar.bz2' suffix.
                    package = package[14:][:-8]
                elif package[-4:] == '.zip':
                    # Remove the 'AROS-YYYYMMDD-' prefix and '.zip' suffix.
                    package = package[14:][:-4]
                elif package[-4:] == '.lha':
                    # Remove the 'AROS-YYYYMMDD-' prefix and '.lha' suffix.
                    package = package[14:][:-4]
                else:
                    continue

                pkgPlatform = pkgArch = pkgFlavour = pkgType = None
                try:
                    pkgPlatform, pkgArch, pkgType = package.split('-', 2)
                    if pkgType.startswith("smp-"):
                        pkgType = pkgType[len("smp-"):]
                        pkgFlavour = "smp"
                except ValueError:
                    pass

                if pkgPlatform is not None and plat is not None and pkgPlatform != plat:
                    continue

                if pkgArch is not None and arch is not None and pkgArch != arch:
                    continue

                if not groups[group].has_key( package ):
                    groups[group][package] = []

                groups[group][package].append( date )

## Output HTML ###############################################################

span = len( dates )

packageHeading = descriptions.get( 'headings', 'package', '' )
dateHeading = descriptions.get( 'headings', 'date', '' )

logsLabel = descriptions.get( 'links', 'build-logs', '' )
downloadLabel = descriptions.get( 'links', 'download', '' )
md5Label = descriptions.get( 'links', 'md5', '' )

print('''
    <table class="layout nightly" border="0" cellpadding="2" cellspacing="1" bgcolor="%(colorFrame)s">
        <tr class="layout nightly" bgcolor="%(colorTH)s">
            <td class="layout invis" width="35%%" rowspan="2"></td>
            <td class="layout padded" align="center" colspan="%(span)d"><b>%(dateHeading)s</b></td>
        </tr>
        <tr class="layout" bgcolor="%(colorTH)s">
''') % vars()

column = span
for date in dates:
    color = Color.blend( colorFileDL, colorBG, span, column )
    year  = date[:4]
    month = date[4:6]
    day   = date[6:8]

    if dltype == "nightly":
        print('''
                    <td class="layout nightly" align="center" bgcolor="%(color)s">
                        <b>%(year)s-%(month)s-%(day)s</b><br>
                        [<a href="https://sourceforge.net/projects/aros/files/nightly/%(date)s/logs/" target="_blank">%(logsLabel)s</a>]
                    </td>
        ''') % vars()
    if dltype == "nightly2":
        print('''
                    <td class="layout nightly" align="center" bgcolor="%(color)s">
                        <b>%(year)s-%(month)s-%(day)s</b><br>
                        [<a href="https://sourceforge.net/projects/aros/files/nightly2/%(date)s/logs/" target="_blank">%(logsLabel)s</a>]
                    </td>
        ''') % vars()
    elif dltype == "snapshots" or dltype == "snapshots2":
        print('''
                    <td class="layout nightly" align="center" bgcolor="%(color)s">
                        <b>%(year)s-%(month)s-%(day)s</b>
                    </td>
        ''') % vars()

    column = column - 1

print('''         </tr>''')

for group in sorted(groups.keys()):
    groupSpan    = span + 1

    try:
        groupKey = string.replace(group, '_', '-').lower()
        groupHeading = descriptions.get( 'headings', groupKey, '' )

        print('''
                <tr class="layout nightly" bgcolor="%(colorTH)s">
                    <td class="layout padded" align="left" colspan="%(groupSpan)s"><b>%(groupHeading)s</b></td>
                </tr>    ''') % vars()

        for package in sorted(groups[group].keys()):
            description = descriptions.get( 'descriptions', package, '' )

            print('''
                    <tr class="layout nightly" valign="middle" bgcolor="%(colorTD)s">
                        <td class="layout padded" valign="top">
                            <p><i>%(package)s</i></p>
                            <p><font size="-1">%(description)s</font></p>
                        </td>
            ''') % vars()

            column = span

            for date in dates:
                if date in groups[group][package]:
                    colorBlended = Color.blend( colorFileDL, colorBG, span, column )
                else:
                    colorBlended = Color.blend( colorFileNA, colorBG, span, column )

                print('''
                            <td class="layout nightly" align="center" bgcolor="%(colorBlended)s">
                ''') % vars()

                if date in groups[group][package]:
                    file = 'AROS-' + date + '-' + package
                    path = os.path.join( root, date, group, file )
                    
                    if os.access(path + '.tar.bz2', os.F_OK):
                        path = path + '.tar.bz2'
                        file = file + '.tar.bz2'
                    elif os.access(path + '.zip', os.F_OK):
                        path = path + '.zip'
                        file = file + '.zip'
                    elif os.access(path + '.lha', os.F_OK):
                        path = path + '.lha'
                        file = file + '.lha'
                    else:
                        path = path + '.php'
                        file = file + '.php'
                    url  = 'https://sourceforge.net/projects/aros/files/%s/%s/%s/%s' % (dltype, date, group, file)
                    urlsuffix = '/download'
                    size = formatSize( os.path.getsize( path ) )
                    print('''
                    <table class="layout" border="0" cellspacing="0" cellpadding="0">
                     <tr class="layout"><td class="layout"></td>
                      <td class="layout" align="center">
                       <span style="float:left">
                        <a href="%(url)s%(urlsuffix)s" target="_blank"><img border="0" src="/images/disk.png" alt="[floppy disk]"></a>
                       </span>
                       <span>
                        <b><a href="%(url)s%(urlsuffix)s" target="_blank">%(downloadLabel)s</a></b><br>
                        %(size)s<br>
                        <a href="%(url)s.md5%(urlsuffix)s" target="_blank">%(md5Label)s</a>&nbsp;
                       </span>
                      </td>
                      <td class="layout"></td>
                     </tr>
                    </table>
                    ''') % vars()
                else:
                    print('''
                    <font color="%(colorGhosted)s">not available</font>
                    ''') % vars()
                print('''</td>''')

                column = column - 1

            print('''        </tr>''')

    except Exception: 
        pass

print('''
    </table>
''')
