#!/bin/bash
VNC_PORT="@@VNC_PORT@@"
SSH_PORT="@@SSH_PORT@@"

PREFIX="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

match_distro="$(cat /etc/*-release |grep DISTRIB_ID )"
DISTRO=${match_distro#"DISTRIB_ID="}

ssh_pub_key="${PREFIX}/id_rsa.pub"
tag_file="${PREFIX}/inventory.tag"


if [ -e ${ssh_pub_key} ]; then
    if ! [ -d "/root/.ssh" ]; then
        echo "Create missing SSH profile ..."
        mkdir -p /root/.ssh
    fi

    tee -a /root/.ssh/authorized_keys < ${ssh_pub_key}
    rm -f ${ssh_pub_key}
fi

sed -i "/s/^#?Port .*$/Port ${SSH_PORT}/" /etc/ssh/sshd_config


fusion_dir="/etc/fusioninventory"
fusion_cfg="$fusion_dir/agent.cfg"
tag=$(sed '1q;d' ${tag_file})

FUSION_PERL_LIB=$(find /usr -name  FusionInventory-Agent)


if [ -f ${fusion_cfg} ];then
    sed -i '/^server\ =/d' ${fusion_cfg}
    sed -i '/^server\=/d' ${fusion_cfg}
    grep -q "${tag}" ${fusion_cfg} || echo "${tag}" >> ${fusion_cfg}
    rm -f ${tag_file}
else
    echo "ERROR: Unable to find fusioninventory config file"
    exit 1
fi


# ----------- VNC server config -----------------
if hash vncserver 2>/dev/null; then
    vnc_cfg=/etc/sysconfig/vncservers
    vnc_servers="VNCSERVERS=\"1:$SUDO_USER\""
    vnc_serverargs="VNCSERVERARGS[1]=\"-geometry 800x600 -nolisten tcp -localhost\""


    if [ -f ${vnc_cfg} ];then
        echo "${vnc_servers}" >> ${vnc_cfg}
        echo "${vnc_serverargs}" >> ${vnc_cfg}
        echo "INFO: Configuring VNC..."
    else
        echo "ERROR: Unable to find VNC config file"
        exit 1
    fi

    # ----------- VNC start ----------
    service vncserver start
    chkconfig --levels 235 vncsever on
fi

echo "INFO: Running initial inventory"
/usr/bin/fusioninventory-agent
