#!/usr/bin/python3
# -*- coding: utf-8 -*-

# Copyright (C) 2012-2014 Stéphane Graber
# Author: Stéphane Graber <stgraber@ubuntu.com>

# 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.
#
# 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 can find the license on Debian systems in the file
# /usr/share/common-licenses/GPL-2

# NOTE: To remove once the API is stabilized
import warnings
warnings.filterwarnings("ignore", "The python-lxc API isn't yet stable")

import argparse
import gettext
import glob
import os
import shutil
import subprocess
import sys

_ = gettext.gettext
gettext.textdomain("edubuntu-server-build-template")

# Some constants
LXC_LIB = "/var/lib/lxc/"
LXC_CACHE = "/var/cache/lxc/"
LXC_TEMPLATE = "tpl-edubuntu-server"
LXC_CONFIGURE = "/usr/share/edubuntu-server/template-configure"

# Begin parsing the command line
parser = argparse.ArgumentParser(
    description=_("Edubuntu server template builder"),
    formatter_class=argparse.RawTextHelpFormatter)

# Optional arguments
parser.add_argument("--cleanup", action="store_true",
                    help=_("Remove an existing template and start over."))

args = parser.parse_args()

# Basic requirements check
## The user needs to be uid 0
if not os.geteuid() == 0:
    print(_("You must be root to run this script. Try running: sudo %s" %
            (sys.argv[0])))
    sys.exit(1)

# Only import lxc now so we don't need to build-depend on it for help2man
import lxc

for path in (LXC_LIB, LXC_CACHE):
    if not os.path.exists(path):
        print(_("%s doesn't exist." % path))
        sys.exit(1)

# In cleanup mode, wipe the LXC cache and any existing template
if args.cleanup:
    if os.path.exists("%s/%s" % (LXC_LIB, LXC_TEMPLATE)):
        shutil.rmtree("%s/%s" % (LXC_LIB, LXC_TEMPLATE))

    for entry in glob.glob("%s/*" % LXC_CACHE):
        shutil.rmtree(entry)

# Check that the container doesn't exist
if os.path.exists("%s/%s" % (LXC_LIB, LXC_TEMPLATE)):
    print(_("The template already exists."))
    sys.exit(1)

# Create a basic container
template = lxc.Container(LXC_TEMPLATE)
if not template.create("ubuntu"):
    print(_("Failed to create the base system."))
    sys.exit(1)

# Run the configuration script
shutil.copy(LXC_CONFIGURE, "%s/%s/rootfs/configure"
            % (LXC_LIB, LXC_TEMPLATE))

with open(os.devnull, "w") as fd:
    configure = subprocess.Popen(["lxc-unshare",
                                  "-s", "PID|MOUNT|IPC|UTSNAME",
                                  "chroot", "%s/%s/rootfs/" %
                                  (LXC_LIB, LXC_TEMPLATE),
                                  "--", "/configure"],
                                 stdout=fd, stderr=fd)

if configure.wait() != 0:
    print(_("Failed to configure the template."))
    sys.exit(1)

os.remove("%s/%s/rootfs/configure" % (LXC_LIB, LXC_TEMPLATE))
