#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Main fork Pisi: Copyright (C) 2005 - 2011, Tubitak/UEKAE
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# 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

# 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 sulin %s' % (output_dir, repository))

        # Install system.base and system.devel
        run('inary --yes-all --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")

        chrun("/usr/bin/inary cp baselayout")
        chrun("/usr/bin/inary cp")

        file(os.path.join(output_dir, "etc/sulin-release"), "w").write("Sulin 2020\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 -t proc proc sandbox/proc')
    run('/bin/mount -t devtmpfs dev sandbox/dev')
    run('/bin/mount -t sys sys sandbox/sys')

def umount_sandbox():
    run('/bin/umount sandbox/sys')
    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", "https://master.dl.sourceforge.net/project/sulinos/SulinRepository/inary-index.xml")
elif cmd == "reset":
    umount_sandbox()
elif cmd == "build":
    pspec = sys.argv[2]
    mount_sandbox()
    run('chroot sandbox inary build %s' % pspec)
    umount_sandbox()
