#!/bin/bash
# Etersoft, 2010
# 2010 (c) Devaev Maxim, <mdevaev@etersoft.ru>
# 2010 (c) Baranov Denis, <baraka@etersoft.ru>
#
# rxsetup - script for fast configuration of NX
#
#####

unlock_nx_user()
{
        passwd -u nx
}

do_chkconfig_on()
{
        chkconfig $1 on 2>/dev/null || update-rc.d $1 defaults
}


start_sshd()
{
        # FIXME Lav: нужно воспользоваться distr_vendor для определения системы
        for sshd in ssh sshd openssh opensshd; do
                if [ -e /etc/init.d/$sshd ]; then
                        /etc/init.d/$sshd start
                        RETVAL="$?"
                        do_chkconfig_on $sshd
                fi
        done

        return "$RETVAL"
}

enable_cupsd()
{
        chmod 755 /usr/sbin/cupsd && \
        chmod 711 /usr/lib/cups/backend/ipp
}

nx_install()
{
        nxsetup --setup-nomachine-key --install
}

start_freenx_server()
{
        SERVICECOMMAND="/etc/init.d/freenx-server"
        do_chkconfig_on freenx-server
        # Without direct dependency to /etc/init.d
        $SERVICECOMMAND start
}

check_expect()
{
	EXPECT=`which expect 2>/dev/null`
	[-n "$EXPECT" ] || echo "Error: please install expect"
}

rxsetup_stages()
{
        local ER=0
        for func in check_expect \
                    unlock_nx_user \
                    start_sshd \
                    enable_cupsd \
                    nx_install \
                    start_freenx_server ; do
            $func || ER=$?
        done
        return $ER
}


##### Main #####
LOG=/var/log/rxsetup.log
echo "Configuring..."
rxsetup_stages 2>&1 | cat >$LOG
if [ "$?" -ne 0 ]; then
        echo "Configuration error, see $LOG for details"
        exit 1
else
        echo "Complete. Now, you may use nxclient for connection to this server"
        rm -f $LOG
fi

