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

# Print command line and run command line
showcmd()
{
	if [ -z "$quiet" ] ; then
		#set_boldcolor $GREEN
		local PROMTSIG="\$"
		[ "$UID" = 0 ] && PROMTSIG="#"
		echo " $PROMTSIG $@"
		#restore_color
	fi >&2
}

# Print command line and run command line
docmd()
{
	showcmd "$@"
	"$@"
}


unlock_nx_user()
{
        docmd passwd -u nx
}

do_chkconfig_on()
{
        CHKCONFIG=$(which chkconfig 2>/dev/null)
        if [ -n "$CHKCONFIG" ] ; then
            docmd $CHKCONFIG $1 on
        else
            docmd update-rc.d $1 defaults
        fi
}


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

enable_cupsd()
{
        docmd chmod 755 /usr/sbin/cupsd || return
        docmd chmod 711 /usr/lib/cups/backend/ipp || return
}

nx_install()
{
        docmd 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 package"
}

clean_freenx()
{
	docmd rm -fr /var/lib/nxserver/home/.ssh/known_hosts
}

selinux_tune()
{
	RESTORECON=$(which restorecon 2>/dev/null)
	test -n "$RESTORECON" && docmd $RESTORECON -Rv /var/lib/nxserver
}

nx_test()
{
	docmd nxsetup --test
}

rxsetup_stages()
{
        local ER=0
        for func in check_expect \
                    unlock_nx_user \
                    selinux_tune \
                    start_sshd \
                    enable_cupsd \
                    nx_install \
                    clean_freenx \
                    start_freenx_server \
                    nx_test; 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 opennx for connection to this server"
        rm -f $LOG
fi

