# Copyright (C) 2009 Julian Andres Klode <jak@debian.org>
#
# debian-cd in Python, using debimg.core
#
import sys, logging
from apt_pkg import SizeToStr
from debimg.core.files import Pool
from debimg.core.image import Image
from debimg.core.resolver import Resolver

BASIC = """
eject
locales
libdevmapper1.02
lvm-common
lvm2
mdadm
aptitude
hotplug
usbutils
console-data
console-common
console-tools
console-cyrillic
console-terminus
pcmcia-cs
pcmciautils
wireless-tools
xfsprogs
jfsutils
dosfsutils
reiserfsprogs
libfribidi0
localization-config
acpid
acpi-support-base
ppp
pppoeconf
pptp-linux
udev
installation-report
openssh-server
cryptsetup
loop-aes-utils
dmraid

/* In etch, libsysfs2-udeb provides libsysfs2 so use this to
 * make sure the deb gets included on the first CD too
 */
libsysfs2

/* Needed for rootless installs. */
sudo

/* libdiscover1-udeb provides libdiscover1 so we have to make sure the
 * deb gets included on the first CD too for arches that get discover1
 */

/* laptop-detect is used by tasksel when checking if the system is a
 * laptop so we have to make sure to get it included on first CD for
 * arches that are know to have laptops
 */

/* grub-pc is used when selecting GPT disk label */

/* #231583: Make life easier for Australian ISP users */
bpalogin

/* multipath-tools-boot is used for multipath support and installed
 * during installation process if multipath is used
 */
multipath-tools-boot

initramfs-tools
busybox
discover
discover1
libdiscover1
grub
grub-pc
laptop-detect
lilo
linux-image-2.6-amd64
linux-headers-2.6-amd64
loop-aes-modules-2.6-amd64
atl2-modules-2.6-amd64
speakup-modules-2.6-amd64
""".splitlines()


def process_file(resolver, fname=None, lines=None):
    for line in lines or open(fname):
        if line.startswith('#include <task-essential'):
            target = '/usr/share/debian-cd/tasks/lenny/task.list.' + line.split('-', 2)[-1].split('>', 1)[0]
            resolver.add_task(*(linex.strip().split()[0] for linex in open(target) if (not linex.startswith('#') and linex.strip() and not linex.endswith('-'))))
        elif line.startswith('#include <task'):
            pass
        elif line.startswith('#include <'):
            target =  line.split('<')[-1].split('>')[0]
            if target == 'debian-installer+kernel':
                process_file(resolver, None, BASIC)
            else:
                process_file(resolver, '/usr/share/debian-cd/tasks/lenny/' + target)
        elif not '*' in line and line.strip():
            try:
                resolver.add_package(line.strip())
            except KeyError, exc:
                #print >> sys.stderr, 'ERROR', exc
                pass




def main():
    #logging.basicConfig(level=logging.INFO, format='%(levelname).1s: %(message)s')
    resolver = Resolver('../example.debimg/apt', 'deb http://ftp.debian.org/debian/ lenny main')
    pool     = Pool('../example.debimg/pool')
    image    = Image(pool, '../example.debimg/image', 620 * 1000 ** 2)

    resolver.add_priority('required')
    resolver.add_priority('important')
    resolver.add_priority('standard')
    process_file(resolver, '/usr/share/debian-cd/tasks/lenny/Debian-kde')
    for group in resolver.groups():
        try:
            image.add_group(group, 'lenny')
        except ValueError, exc:
            print >> sys.stderr,  'ERROR', exc
            break

    print >> sys.stderr, 'Used (sectors):', SizeToStr(image.sectors_used), 'of', SizeToStr(image.sectors_total)
    print >> sys.stderr, 'Used (bytes):', SizeToStr(image.sectors_used * 2048),
    print >> sys.stderr, 'of', SizeToStr(image.sectors_total * 2048)
    print >> sys.stderr, '=====>', 100 * image.sectors_used // image.sectors_total, '%'

    for fname in sorted(image.files, key=lambda fname: fname.split('/')[-1]):
        if fname.endswith('.deb'):
            print fname.split('/')[-1]

if __name__ == '__main__':
    main()
