#!/bin/sh

. /etc/blackPanther-default-apps.conf
####### 
#*********************************************************************************************************
#*   __     __               __     ______                __   __                      _______ _______   *
#*  |  |--.|  |.---.-..----.|  |--.|   __ \.---.-..-----.|  |_|  |--..-----..----.    |       |     __|  *
#*  |  _  ||  ||  _  ||  __||    < |    __/|  _  ||     ||   _|     ||  -__||   _|    |   -   |__     |  *
#*  |_____||__||___._||____||__|__||___|   |___._||__|__||____|__|__||_____||__|      |_______|_______|  *
#* http://www.blackpantheros.eu | http://www.blackpanther.hu - kbarcza[]blackpanther.hu * Charles Barcza *
#*************************************************************************************(c)2002-2018********
##   blackPanther Hostname Configuration
#####
debug=$(echo $@ | grep DEBUG && echo 1)
#debug=syslog

dbg ()
{
    if [ "$debug" = "syslog" ];then
	enter=""
       	logger ${@}
    elif [ -n "$debug" ]; then
	enter="\n"
	quiet=-q
        space='echo'
       	$SETCOLOR_FAIL
       	echo -en "DBG: ${@} $enter"
       	$SETCOLOR_NORMAL
    fi 
}


NAME=$(hostname)
if [ ! -n "$(echo $NAME | grep -e '[a-z]' -e '[A-Z]' )" ];then
    hostnamectl set-hostname $(cat /etc/hostname | head -n 1)
fi

    user=$(ps aux | awk '{print $1" "$11}' | sed -e 's|root.*||'| grep -v sddm |grep dbus-launch | awk '{print $1}' | sed 's|+||')
    longname=$(users | sed 's/root//' | grep ${user})
    [ ! -n "$longname" ]&&longname=$user

    if [ "$(echo $longname |grep '^[a-zA-Z]')" = "" ];then
	dbg "Not named user, get from group id"
	usernum=`echo "$longname" | grep '^[0-9]'`
	for anuser in `cat /etc/group | grep "$usernum" | awk -F: '{ print $1}'` ;do 
	    users="$anuser $(echo "$longname" | sed "s|$usernum||" | uniq)"
	done
    else
	dbg "Great this is a named $longname"
	users=$longname
    fi    
    export PATH=/usr/lib/blackPanther-default-apps/bin:$PATH
    export DISPLAY=:0


SYSSET=$(su -c "hostname"  $users)
USERSET=$(su -c "xauth list | sed 's|/.*||'"  $users)

if [ "$SYSSET" != "$USERSET" ];then
	dbg "Different $SYSTET ! Run hotnamectl set-hostname $USERSET"
    [ -n "$USERSET" ]&&hostnamectl set-hostname $USERSET 
    exit
fi
