#!/bin/bash

# usefull debugging tools pavucontrol htop x11vnc

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
fi

export USER=neko
export SCREEN_WIDTH=1280
export SCREEN_HEIGHT=720
export SCREEN_DEPTH=24
export DISPLAY=:99.0

set -ex

#
# create log folders
if [ ! -L /var/log/neko ]; then
  mkdir -p logs/neko

  ln -s /workspace/.docker/logs/neko /var/log/neko 
  
  chown -R $USER logs
  chown -R $USER /var/log/neko
fi

#
# clean up old logs
if [ -d logs ]; then
  rm -rf logs/*.log
fi

#
# copy neko config
mkdir -p /etc/neko/supervisord
cp files/dbus /usr/bin/dbus
cp files/default.pa /etc/pulse/default.pa
cp files/supervisord.conf /etc/neko/supervisord.conf
cp files/xorg.conf /etc/neko/xorg.conf
cp files/openbox.xml /etc/neko/openbox.xml

chmod +x /usr/bin/dbus

#
# remove old configs
rm -rf /etc/neko/supervisord/*.conf

#
# copy dist files
if [ -f ../server/bin/neko ]; then
  cp ../server/bin/neko /usr/bin/neko
fi

if [ -d ../client/dist ]; then
  cp -R ../client/dist /var/www/
fi

#
# setup pules
if [ ! -f /home/$USER/.config/pulse/client.conf ]; then
  mkdir -p /home/$USER/.config/pulse
  echo "default-server=unix:/tmp/pulseaudio.socket" > /home/$USER/.config/pulse/client.conf
  chown -R $USER /home/$USER/.config;
fi

#
# run setup for browser 
case $1 in
  firefox) ./files/firefox/test ;;
  chromium) ./files/chromium/test ;;
  *) ./files/chromium/test ;;
esac

#
# clean up old sessions
rm -rf /home/$USER/.dbus

#
# run supervisord
supervisord --configuration ./files/supervisord.conf