#!/usr/bin/env python
#
# Copyright 2009 Canonical Ltd.
#
# 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 2, 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 with your
# system, in /usr/share/common-licenses/GPL-2.  If not, write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
#
# Authors: Chris Cheney <chris.cheney@canonical.com>
#          Emmet Hikory <emmet.hikory@canonical.com>

import ConfigParser
import os
import subprocess
import sys

#modify proejct-generic project.cfg.in to project-specific project.cfg using contents of ./PROJECT
#and update.cfg.in to update.cfg
#and metapackage-map.in to metapackage-map
f_proj = open ("./PROJECT", "r")
project_name = f_proj.read()
f_proj.close()
cfg = "project.cfg"
cmd =["sed 's_PROJECT_" + project_name[:len(project_name)-1] + "_g' " + cfg + ".in > " + cfg]
subprocess.Popen(cmd, shell=True, cwd = "./", stdout=subprocess.PIPE ).communicate()
cfg = "update.cfg"
cmd =["sed 's_PROJECT_" + project_name[:len(project_name)-1] + "_g' " + cfg + ".in > " + cfg]
subprocess.Popen(cmd, shell=True, cwd = "./", stdout=subprocess.PIPE ).communicate()
cfg = "metapackage-map"
cmd =["sed 's_PROJECT_" + project_name[:len(project_name)-1] + "_g' " + cfg + ".in > " + cfg]
subprocess.Popen(cmd, shell=True, cwd = "./", stdout=subprocess.PIPE ).communicate()


def getRepoURI(mirror, dist, suite, arch):
    archive_base_default = config.get(mirror, 'archive_base/default')
    try:
        archive_base = config.get(mirror, 'archive_base/%s' % arch)
    except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
        if archive_base_default is not None:
            archive_base = archive_base_default
        else:
            error_exit('no archive_base configured for %s' % arch)
    if not arch == 'source':
        return(archive_base + 'dists' + '/' + dist + '/' + component + '/' + 'binary-' + arch)
    else:
        return(archive_base + 'dists' + '/' + dist + '/' + component + '/' + arch)


config = ConfigParser.SafeConfigParser()
config_file = open('project.cfg')
config.readfp(config_file)
config_file.close()

project = config.get('DEFAULT', 'name')
seeds = config.get('DEFAULT', 'seeds')
seed_base = config.get('DEFAULT', 'seed_base')
suites = config.get('DEFAULT', 'suites').split()
architectures = config.get('DEFAULT', 'architectures')
dist_base = config.get('DEFAULT', 'dist_base')

# cleanup
os.system("rm -rf " + project)
os.system("rm -f update.cfg")

# Download all Packages/Sources files and create repo
for suite in suites:
    dist = config.get(suite, 'dist')
    mirror = config.get(suite, 'mirror')
    for component in config.get(suite, 'components').split():
        for architecture in architectures.split():
            print 'Downloading ' + suite + ' ' + component + ' ' + architecture
            path = project + '/' + 'dists' + '/' + dist_base + '/' + project + '/' + 'binary-' + architecture
            os.system('mkdir -p ' + path)
            #print 'URL is wget -q -O- ' + getRepoURI(mirror, dist, component, architecture) + '/Packages.bz2 | bunzip2 >> ' + path + '/' + 'Packages'
            os.system('wget -q -O- ' + getRepoURI(mirror, dist, component, architecture) + '/Packages.bz2 | bunzip2 >> ' + path + '/' + 'Packages')

        print 'Downloading ' + suite + ' ' + component + ' ' + 'source'
        path = project + '/' + 'dists' + '/' + dist_base + '/' + project + '/' + 'source'
        os.system('mkdir -p ' + path)
        #print 'URL is wget -q -O- ' + getRepoURI(mirror, dist, component, 'source') + '/Sources.bz2 | bunzip2 >> ' + path + '/' + 'Sources'
        os.system('wget -q -O- ' + getRepoURI(mirror, dist, component, 'source') + '/Sources.bz2 | bunzip2 >> ' + path + '/' + 'Sources')


# Create Release file for repo
release_f = open(project+'/Release', 'w')
print "current directory" + os.getcwd()
print >> release_f, 'Components: ' + project
release_f.close()
os.system('cd ' + project + '/dists && apt-ftparchive release ' + dist_base + ' >> ../Release')
os.system('mv ' + project + '/Release ' + project + '/' + 'dists' + '/' + dist_base)

# Create Germinate update.cfg
cfg_f = open('update.cfg', 'w')
print >> cfg_f, '[DEFAULT]'
print >> cfg_f, 'dist: ' + dist_base
print >> cfg_f, ''
print >> cfg_f, '[' + dist_base + ']'
print >> cfg_f, 'seeds: ' + seeds
print >> cfg_f, 'architectures: ' + architectures
print >> cfg_f, 'archive_base/default: file://' + os.getcwd() + '/' + project + '/'
print >> cfg_f, 'seed_base: ' + seed_base
print >> cfg_f, 'seed_dist: ' + project
print >> cfg_f, 'components: ' + project
cfg_f.close()
