#!/bin/bash
config_dir=/etc/nyquist
eeprom_dir=/sys/devices/platform/bone_capemgr
umask 000

FILE_HOSTNAME=$(cat /etc/hostname)
APPLIANCE_MAC=$(ip link show eth0 | awk '/ether/ {print $2}' | sed 's/://g')
HOSTS_LOC="/etc/hosts"

log_setup () {
  # Best effort system date progression for managing logs
  logf_sorted=($(ls -t /var/log))
  epoch_latest_log=$(stat -c %Y /var/log/${logf_sorted[0]})
  epoch_now=$(date +%s)
  if [ $epoch_now -lt $epoch_latest_log ]
  then
    echo "Time skew detected advancing the time from \"`date`\" to \"`date -d \"@$epoch_latest_log\"`\""
    date -s "@$epoch_latest_log" > /dev/null
  fi

  # Sync up log file modification time to NTP time when present
  systemd-run --unit ntpcheck --no-block --service-type=idle bash -c 'while [ true ]; do /usr/sbin/ntp-wait -s 3600; [ $? -eq 0 ] && break || sleep 5; done; find /var/log -type f ! -name *.[0-9]* -exec touch {} +'
}

appliance_board_support () {
	unset STATION_PREFIX
	if [ $1 -eq 2 ]; then
		SW_POS=(/sys/class/gpio/gpio45/value)
		SUFFIXES=(1 2)
	elif [ $1 -eq 4 ]; then
		SW_POS=(/sys/class/gpio/gpio45/value /sys/class/gpio/gpio23/value)
		SUFFIXES=(A AB C CD)
	fi
	for idx in ${!SW_POS[*]}; do
		DUAL=$(cat ${SW_POS[$idx]})
		echo "AMP Dual: $DUAL"
		STATION_PREFIX=${STATION_PREFIX}${SUFFIXES[$(($idx * 2 + $DUAL))]}
	done
	echo "Stations Prefix: $STATION_PREFIX"
	STATION_PREFIX="-${STATION_PREFIX}"
	export APPLIANCE_PART=${APPLIANCE_BOARD//\"}
} 

: ${device_id:=nq-voip}

# Create temporary storage location for PHP
mkdir -p /run/php5/sessions
chmod 1733 /run/php5/sessions

eeprom_status="not found"
for slot in ${eeprom_dir}/slot-*
do
	if [ -d ${slot} ]; then
		read -N 5 val < ${slot}/manufacturer
		if [ "x${val,,*}" == "xbogen" ]; then
			read APPLIANCE_BOARD < ${slot}/board-name
			read APPLIANCE_PART < ${slot}/part-number
			read APPLIANCE_SERIAL < ${slot}/serial-number
			eeprom_status="found"
			break
		fi
	fi
done

export APPLIANCE_BOARD=\"${APPLIANCE_BOARD:=}\"
export APPLIANCE_PART=${APPLIANCE_PART:=$device_id}
export APPLIANCE_SERIAL=${APPLIANCE_SERIAL:=}
export PATH=/usr/local/bin:${PATH}

if [ "${APPLIANCE_PART/asb}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asoundasb_loop.txt /etc/asound.conf
	#ln -sf /etc/nyquist/asoundasb.txt /etc/asound.conf
	PART_SERVICES="while [ true ]; do systemctl --quiet is-active multi-user.target; [ \$? -eq 0 ] && break || sleep 5; done; systemctl start appliance-websocket"
elif [ "${APPLIANCE_PART/mix}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asoundmixer.txt /etc/asound.conf
	PART_SERVICES="systemctl start dsp-websocket"
elif [ "${APPLIANCE_PART/voip}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asoundvoip.txt /etc/asound.conf
elif [ "${APPLIANCE_PART/s810v2}" != ${APPLIANCE_PART} -o "${APPLIANCE_PART/s810v3}" != ${APPLIANCE_PART} -o "${APPLIANCE_PART/edp01}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asounds810v2.txt /etc/asound.conf
	PART_SERVICES="systemctl start dsp-websocket"
elif [ "${APPLIANCE_PART/a?xxx}" != ${APPLIANCE_PART} ]; then
	#we need to handle amplifiers differently, because we are interested in the APPLIANCE_BOARD, not APPLIANCE_PART
	NUM_CHANNELS=${APPLIANCE_PART: 4:1}
	if [ "${APPLIANCE_PART/g2}" != "${APPLIANCE_PART}" ]; then
		ln -sf /etc/nyquist/asounda${NUM_CHANNELS}g2.txt /etc/asound.conf
	else
		ln -sf /etc/nyquist/asounda${NUM_CHANNELS}.txt /etc/asound.conf
	fi
	PART_SERVICES="systemctl start dsp-websocket"
	appliance_board_support ${NUM_CHANNELS}
elif [ "${APPLIANCE_PART/ga10p}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asoundga10px_loop.txt /etc/asound.conf
	[ "${APPLIANCE_PART/ga10pv}" != ${APPLIANCE_PART} ] && PART_SERVICES="while [ true ]; do systemctl --quiet is-active multi-user.target; [ \$? -eq 0 ] && break || sleep 5; done;/usr/local/bin/init-display"
elif [ "${APPLIANCE_PART/ga20p}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asoundga20.txt /etc/asound.conf
	PART_SERVICES="systemctl start dsp-websocket"
elif [ "${APPLIANCE_PART/paxxx}" != ${APPLIANCE_PART} ]; then
	#we need to handle PA differently, because we are interested in the APPLIANCE_BOARD, not APPLIANCE_PART
	ln -sf /etc/nyquist/asoundpaxxx.txt /etc/asound.conf
	PART_SERVICES="systemctl start dsp-websocket"
	export APPLIANCE_PART=${APPLIANCE_BOARD//\"}
elif [ "${APPLIANCE_PART/ga400p}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asoundga400p.txt /etc/asound.conf
	PART_SERVICES="systemctl start dsp-websocket"
elif [ "${APPLIANCE_PART/ga40p3}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asoundga40.txt /etc/asound.conf
	PART_SERVICES="systemctl start dsp-websocket"
elif [ "${APPLIANCE_PART/ser20p2}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asoundser20p2.txt /etc/asound.conf
	PART_SERVICES="systemctl start dsp-websocket"
elif [ "${APPLIANCE_PART/dsc01}" != ${APPLIANCE_PART} ]; then
	ln -sf /etc/nyquist/asoundser20p2.txt /etc/asound.conf
	PART_SERVICES="systemctl start dsp-websocket"
else
	ln -sf /dev/null /etc/asound.conf
fi

APPLIANCE_PART_MAP=${APPLIANCE_PART/voip/spkr}
APPLIANCE_HOSTNAME=${APPLIANCE_PART_MAP^^*}-${APPLIANCE_MAC^^*}

echo "Appliance EEPROM was ${eeprom_status}"
echo "APPLIANCE_BOARD=${APPLIANCE_BOARD:=}" > /run/appliance-env
echo "APPLIANCE_PART=${APPLIANCE_PART:=$device_id}${STATION_PREFIX}" >> /run/appliance-env
echo "APPLIANCE_SERIAL=${APPLIANCE_SERIAL:=}" >> /run/appliance-env
echo "PATH=${PATH}" >> /run/appliance-env

systemctl set-environment APPLIANCE_BOARD="${APPLIANCE_BOARD}" APPLIANCE_PART=${APPLIANCE_PART} APPLIANCE_SERIAL=${APPLIANCE_SERIAL} PATH=/usr/local/bin:${PATH}

# Always ensure /etc/hosts has the correct hostname entries
sed -i '/127.0.0.1.*\(NQ-\|arm\)/d' $HOSTS_LOC
echo -e "127.0.0.1\t${APPLIANCE_HOSTNAME}.localdomain\t${APPLIANCE_HOSTNAME}" >> $HOSTS_LOC

# Update /etc/hostname and reboot if it differs from computed hostname
if [ -n "${FILE_HOSTNAME/$APPLIANCE_HOSTNAME}" ]; then
	echo "${APPLIANCE_HOSTNAME}" > /etc/hostname
	systemctl --force reboot
fi

log_setup

# Start any part specific service
if [ -n "${PART_SERVICES}" ]; then
	systemd-run --unit ${APPLIANCE_PART}-kickoff --no-block --service-type=idle bash -c "$PART_SERVICES"
fi
