#!/usr/bin/perl -s

use strict;
use warnings;

use EBox;
use EBox::Gettext;
use EBox::Global;
use Error qw(:try);

if (scalar @ARGV == 2) {
    my $chroot = $ARGV[0];
    my $apps = $ARGV[3];
    if ( -f "/opt/ltsp/images/$chroot.img" ) {
        EBox::init();

        my $ltsp = EBox::Global->modInstance('ltsp');

        $ltsp->st_set_string('work', 'install');
        $ltsp->st_set_string('error', '');

        print "Installing applications into $chroot image: $apps\n";

        my $CHROOT_DIR = "/opt/ltsp/$chroot";
        my $cmd = "chroot $CHROOT_DIR mount -t proc none /proc "
                  . "&& chroot $CHROOT_DIR apt-get update "
                  . "&& chroot $CHROOT_DIR env LTSP_HANDLE_DAEMONS=false apt-get -y install $apps "
                  . "&& umount /opt/ltsp/$chroot/proc "
                  . "&& ltsp-update-image --arch $chroot";  # --arch is actually the chroot name

        try {
            # TODO: add more messages to ltsp.log (with timestamps)
            EBox::Sudo::root("$cmd >> /var/log/zentyal/ltsp.log");
        } otherwise {
            $ltsp->st_set_string('error', __('Applications installation failed'));
            print "Applications installation failed. Check /var/log/zentyal/ltsp.log for details.\n";
            # In case the command failed before the umount
            EBox::Sudo::root("umount /opt/ltsp/$chroot/proc > /dev/null");
        } finally {
            $ltsp->st_set_string('work', 'none');
        };
    } else {
        print "/opt/ltsp/images/$chroot.img does not exist.\n";
    }
} else {
    print "Usage: install-local-applications chroot apps\n";
}
