#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2011 TUBITAK/UEKAE
#
# 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 of the License, or (at your
# option) any later version. Please read the COPYING file.
#

import os
import shutil
import subprocess
import sys
import stat
import time
import socket
import getopt

def chroot_comar(image_dir):
    if os.fork() == 0:
        try:
            os.makedirs(os.path.join(image_dir, "var/db"), 0o700)
        except OSError:
            pass
        os.chroot(image_dir)
        if not os.path.exists("/var/lib/dbus/machine-id"):
            run("/usr/bin/dbus-uuidgen --ensure")
        run("/sbin/start-stop-daemon -b --start --pidfile /var/run/dbus/pid --exec /usr/bin/dbus-daemon -- --system")
        sys.exit(0)

    # wait comar to start
    timeout = 5
    wait = 0.1
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    while timeout > 0:
        try:
            sock.connect("%s/var/run/dbus/system_bus_socket" % image_dir)
            return True
        except:
            timeout -= wait
        time.sleep(wait)
    return False

# run command and terminate if something goes wrong
def run(cmd, ignore_error=False):
    print(cmd)
    ret = os.system(cmd)
    if ret and not ignore_error:
        print(("%s returned %s" % (cmd, ret)))
        sys.exit(1)

def create_sandbox(output_dir, repository):
    try:
        # Add repository of the packages
        run('inary --yes-all --destdir="%s" add-repo pardus %s' % (output_dir, repository))

        # Install system.base and system.devel
        run('inary --yes-all --ignore-comar --ignore-file-conflicts -D"%s" it -c system.base -c system.devel' % output_dir)

        # Create /etc from baselayout
        path = "%s/usr/share/baselayout/" % output_dir
        path2 = "%s/etc" % output_dir
        for name in os.listdir(path):
            run('cp -p "%s" "%s"' % (os.path.join(path, name), os.path.join(path2, name)))

        # Create character device
        os.mknod("%s/dev/null" % output_dir, 0o666 | stat.S_IFCHR, os.makedev(1, 3))
        os.mknod("%s/dev/console" % output_dir, 0o666 | stat.S_IFCHR, os.makedev(5, 1))

        # Create urandom character device
        os.mknod("%s/dev/urandom" % output_dir, 0o666 | stat.S_IFCHR, os.makedev(1, 9))

        # run command in chroot
        def chrun(cmd):
            run('chroot "%s" %s' % (output_dir, cmd))

        chrun("/sbin/ldconfig")
        chrun("/sbin/update-environment")
        chroot_comar(output_dir)

        chrun("/usr/bin/inary cp baselayout")
        chrun("/usr/bin/inary cp")
        chrun("/usr/bin/hav call baselayout User.Manager setUser 0 'Root' '/root' '/bin/bash' 'pardus' '' ")

        # Now it is 2011 release
        file(os.path.join(output_dir, "etc/pardus-release"), "w").write("Pardus 2011\n")

    except KeyboardInterrupt:
        run('umount %s/proc' % output_dir, ignore_error=True)
        run('umount %s/sys' % output_dir, ignore_error=True)
        sys.exit(1)

def mount_sandbox():
    run("mkdir -p tmpfs")
    run("mount -t tmpfs -o size=1024M,mode=0744 tmpfs tmpfs/")
    run("mkdir -p sandbox")
    run("mount -t aufs -o br=tmpfs=rw:base=ro none sandbox/")
    run('/bin/mount --bind /proc sandbox/proc')
    run('/bin/mount --bind /dev sandbox/dev')

def umount_sandbox():
    run('/bin/umount sandbox/dev')
    run('/bin/umount sandbox/proc')
    run('/bin/umount sandbox')
    run('/bin/umount tmpfs')

cmd = sys.argv[1]

if cmd == "create":
    create_sandbox("base", "http://192.168.3.110/pardus-2009/inary-index.xml.bz2")
elif cmd == "reset":
    umount_sandbox()
elif cmd == "build":
    pspec = sys.argv[2]
    mount_sandbox()
    run('chroot sandbox inary build %s' % pspec)
    umount_sandbox()
