#!/usr/bin/env bash

#This is run every time X is starting
#Can be symlinked to users .xinitrc
#Exec bit is important to run script in bash, not sh

source /etc/environment
export $(cat /etc/environment | grep -vE '^$|^#' | cut -d= -f1) #export all variables from file

[[ -f $RIG_CONF ]] && source $RIG_CONF

if [[ $X_DISABLED == 1 || $MAINTENANCE == 2 ]]; then
	echo "X Server is disabled, exiting"
	exit 0
fi

export PATH="./:/hive/bin:/hive/sbin:$PATH"

[ -z "$HOME" ] && HOME="/root"
[ -z "$XDG_CONFIG_HOME" ] && export XDG_CONFIG_HOME="$HOME/.config"
[ -z "$XDG_DATA_HOME" ] && export XDG_DATA_HOME="$HOME/.local/share"

#if no connected monitor set resolution for x11vnc
re='\<connected\>' #find word
if [[ ! `xrandr -q` =~ $re ]]; then
    echo "XRANDR: Did not find connected monitor will set fake resolution"
    xrandr --fb 1024x768
else
    echo "XRANDR: Connected monitor detected will use native resolution"
fi

# enable kill X server with keyboard
setxkbmap -option "terminate:ctrl_alt_bksp"

systemctl status getty@tty1 > /dev/null 2>&1 && HIDDEN_MODE_ENABLE=1

if [[ $X_NOGUI == 1 || $HIDDEN_MODE_ENABLE == 1 || "$(grep '/ ' /proc/mounts | awk '{print $1}')" == "tmpfs" ]]; then
	echo 0 > /run/hive/xready
	sleep infinity
	exit
fi

#-nopw
#> /var/log/x11vnc.log 2>&1 &

# display no sleep
#setterm -blank 0
#setterm -powersave off
#xset -dpms

# taskbar
tint2 &

# wallpaper
(sleep 2 && which feh && feh --bg-fill --no-fehbg /hive/share/images/wallpaper.jpg) &

termcmd=""
[[ -e /home/user/xinit.user.sh ]] && termcmd="bash /home/user/xinit.user.sh;"

win_name="Hiveon"
tab_name="X-Console"
termargs="--replace --maximise --title=$win_name --tab-name=$tab_name --hide-menubar"

(lsb_release -a 2>&1 | grep -q '16\.04') && termargs+=' --disable-sm'

[[ -f /usr/bin/alacritty ]] && termargs=""

x-terminal-emulator $termargs -e bash -c "$termcmd motd boot; firstrun; bash" &

echo 1 > /run/hive/xready

# Startx VNC server (if it's enabled)
remote-connections x11vnc_start

openbox-session
