#!/usr/bin/env python3
# Copyright 2014 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; version 2.1.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Benjamin Zeller<benjamin.zeller@canonical.com>

import signal
import subprocess
import sys
import os
import uuid
import shutil
import dbus

chroot_name_prefix = os.getenv('CLICK_CHROOT_SUFFIX', "click")

architecture = os.getenv('CLICK_SDK_ARCH')
if architecture is None:
    print("Need to set CLICK_SDK_ARCH non-empty")
    sys.exit(-1)

framework = os.getenv('CLICK_SDK_FRAMEWORK')
if framework is None:
    print("Need to set CLICK_SDK_FRAMEWORK non-empty")
    sys.exit(-1)

args = sys.argv[1:]
if any("help" not in s for s in args):
    work_dir = os.getcwd()
    if (os.path.exists(work_dir+"/CMakeCache.txt")):
        print("-- Removing build artifacts")
        shutil.rmtree(work_dir+'/CMakeFiles')
        os.remove(work_dir+"/CMakeCache.txt")
        os.remove(work_dir+"/cmake_install.cmake")
        os.remove(work_dir+"/Makefile")

subproc    = None
session_id = ""
click      = shutil.which("click")
pre_spawned_session = False

if( click is None ):
    print("Could not find click in the path, please make sure it is installed")
    sys.exit(1)

def exit_gracefully(arg1,arg2):
    print("Exiting gracefully")
    if(subproc is not None):
        try:
            subproc.kill()
        except ProcessLookupError:
            #process is already gone
            pass

    if (not pre_spawned_session):
        subprocess.call([click, "chroot","-a",architecture,"-f",framework,"-n",chroot_name_prefix,"end-session",session_id],stdout=subprocess.DEVNULL)

    sys.exit(1)

signal.signal(signal.SIGTERM, exit_gracefully)
signal.signal(signal.SIGINT , exit_gracefully)
signal.signal(signal.SIGHUP , exit_gracefully)

#only ask the chroot-agent if we use the default click prefix
if chroot_name_prefix == "click":
    try:
        sessionBus = dbus.SessionBus()
        clickChrootAgent = sessionBus.get_object('com.ubuntu.sdk.ClickChrootAgent','/com/ubuntu/sdk/ClickChrootAgent')
        clickChrootAgentIFace = dbus.Interface(clickChrootAgent,dbus_interface='com.ubuntu.sdk.ClickChrootAgent')
        session_id = clickChrootAgentIFace.spawnSession(framework,architecture)
    except dbus.exceptions.DBusException:
        session_id = ""

if (len(session_id) == 0):
    session_id   = str(uuid.uuid4())
    pre_spawned_session = False
else:
    pre_spawned_session = True

if ( not pre_spawned_session ):
    success = subprocess.call([click, "chroot","-a",architecture,"-f",framework,"-n",chroot_name_prefix,"begin-session",session_id],stdout=subprocess.DEVNULL)

sys.stdout.flush()
sys.stderr.flush()
subproc = subprocess.Popen([click, "chroot","-a",architecture,"-f",framework,"-n",chroot_name_prefix,"run","-n",session_id]+["cmake"]+args,stdout=sys.stdout, stderr=sys.stderr)
subproc.wait()
sys.stdout.flush()
sys.stderr.flush()

if (not pre_spawned_session):
    subprocess.call([click, "chroot","-a",architecture,"-f",framework,"-n",chroot_name_prefix,"end-session",session_id],stdout=subprocess.DEVNULL)

sys.exit(subproc.returncode)
