#!/bin/bash


# 'here' is where this script is located, likely /bin
here=$(dirname $0)
source $here/hy_functions

flavor=$(basename $0)

# We don't run cron in the image, so running the logrotate script upon
# startup/sync seems reasonable enough (LP: #838415)
/bin/sh /etc/cron.daily/logrotate

# make startup obvious
bars="--------------------------------------------------------------------"
echo -e "\n\n${bars}\n--- $0 - $(date)\n${bars}" >> $UFA_LOG

# Turn the build stamp into a single line and print it.
log "Build '$(tr '\n' ' ' < /etc/buildstamp)'"


if [[ -n "$UFA_TIMEZONE" ]]
then
	log "Received UFA_TIMEZONE: $UFA_TIMEZONE"
	change_timezone $UFA_TIMEZONE 2>&1 >> $UFA_LOG
fi


# Set ufa's locale and language
# UFA_LANG is formatted as 'll-CC', for example 'en-US'
#
# http://www.gnu.org/software/gettext/manual/gettext.html#Locale-Names
# We expect ufa to be invoked explicitly with LANG and LANGUAGE set
# LANG=en_US.UTF-8 # specific lanuage set ll_CC.encoding
# LANGUAGE=en_US:en # search path of languages
#
if [[ -z "$UFA_LANG" ]]
then
	log "Environment variable UFA_LANG expected, not found. Continuing."
else
	LOCALE="/etc/default/locale"
	log "Received UFA_LANG: $UFA_LANG, creating $LOCALE"

	rm $LOCALE
	echo "# This file created by $0" >> $LOCALE

	ufa_lang=$(echo $UFA_LANG|sed s/-/_/)  # temp fix
	LANG="$ufa_lang.UTF-8"

	# (LP: #833730)
	echo "LC_ALL=$LANG" >> $LOCALE
	echo "LANG=$LANG" >> $LOCALE
	echo "LANGUAGE=$ufa_lang:en" >> $LOCALE
	# (LP: #844000)
	echo "GDM_LANG=$ufa_lang" >> $LOCALE

	locale_gen $LANG 2>&1 >> $UFA_LOG
fi

rm /etc/resolv.conf

if [[ -z "$UFA_DOMAIN_NAME_SERVERS" ]]
then
	log "Creating default /etc/resolv.conf"
	echo "nameserver 8.8.8.8" >> /etc/resolv.conf
else
	log "Received Android DNS: $UFA_DOMAIN_NAME_SERVERS"
	change_dns "$UFA_DOMAIN_NAME_SERVERS"
fi

if [[ $flavor = "ufa_sync" ]]
then
	log "$0 completed"
	exit 0
fi



export TERM=xterm
export USER=root
export COLORTERM=1
export TMPDIR=/tmp

rm -rf /tmp/* /tmp/.*

rm -rf /var/run/*
chmod -R 777 /var/lib

mkdir -p /var/run/dbus
mkdir -p /etc/dbus-1/session.d/
mkdir -p /udev
chmod 777 /udev

if ! ck_dir /dev/shm
then
	log "transitional: $0 mounted /dev/shm"
	mkdir /dev/shm
	mount -t tmpfs -r -w none /dev/shm
fi

udevd --daemon
udevadm trigger

chown messagebus:messagebus /var/run/dbus
dbus-uuidgen --ensure

dbus-daemon --system --fork
console-kit-daemon

#set_fb

lightdm -c /usr/share/lightdm-ufa.conf &
#gdm &

# The intention of this busy wait loop is for gdm auto-login to complete
# and desktop to become ready before we exit the script and return to our
# caller. See HY-26 for further motivation.
for i in $( seq 1 60 )
do
	ps aux | grep indicator-datetime | grep -qv grep
	if [[ $? -eq 0 ]]
	then
		log "indicators started after $i seconds"
		sleep 1		# sleep 1 extra second for -datetime to start
		exit 0
	fi

	sleep 1
done

log "indicators did not start!"
exit 1
