#!/bin/sh
# Instead of running the application directly, we run it from this script.
# Running from this script preserves the ulimit settings that were set
# in /etc/init.d/b2qt-settings-sh which allows a core dump to be generated if a crash occurs.
# b2qt-settings.sh will exit after being run which takes the ulimit settings with it
# When we run the app from this script, it does not exit which preserves the ulimit settings
# Documentation of ulimit says: "The ulimit utility shall set or  report  the  file-size
# writing limit imposed on files written by the shell and its child processes"


#######################################################################
#  Set the Qt Library path, this is thought to be needed if we attempt to
#  run a Qt5.05 application on the 5.12 target.  The library path will
#  point to the correct location of Qt libraries
#######################################################################
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/qt5_12_3/lib

psplash --no-console-switch &
until [ -p /var/tmp/psplash_fifo ]; do msleep 1; done
psplash-write "PROGRESS 0"

if [ -f /bsp_version.txt ]; then
  bsp_version=$(cat /bsp_version.txt | cut -d ' ' -f2)
else
  bsp_version=$(cat /version.txt | cut -d ' ' -f2)
fi
if [[ "$bsp_version" == "32" ]] || [[ "$bsp_version" == "33" ]]; then
  insmod /opt/Bunn/application/linuxSystemFiles/bsp32/usbserial.ko
  insmod /opt/Bunn/application/linuxSystemFiles/bsp32/ftdi_sio.ko
else # 34_rc1 and beyond
  insmod /opt/Bunn/application/linuxSystemFiles/bsp34/usbserial.ko
  insmod /opt/Bunn/application/linuxSystemFiles/bsp34/ftdi_sio.ko
fi

grep '^#cron' /etc/syslog.conf &> /dev/null
if [ $? -eq 0 ]; then
  sed -i 's/#\(.*cron.*\)/\1/' /etc/syslog.conf
  /etc/init.d/syslog restart
fi

# this stops /var/log/cron.log messages every minute like:
# crond[1005]: (root) WRONG FILE OWNER (/var/spool/cron/root)
chown root:root /var/spool/cron/root

if [ ! -f /etc/cron.hourly/bunn ]; then
  chown root /etc/crontab
  sed -i 's/#\(.*hourly.*\)/\1/' /etc/crontab
  ln -s /opt/Bunn/application/linuxSystemFiles/cron.hourly.sh /etc/cron.hourly/bunn
  /etc/init.d/crond restart
fi

if [ ! -f /etc/cron.daily/bunn ]; then
  chown root /etc/crontab
  sed -i 's/#\(.*daily.*\)/\1/' /etc/crontab
  ln -s /opt/Bunn/application/linuxSystemFiles/cron.daily.sh /etc/cron.daily/bunn
  /etc/init.d/crond restart
fi

# cannot create symlink since /opt/Bunn/application is mounted after udev runs
\cp /opt/Bunn/application/linuxSystemFiles/99-usb-auto-mount.rules /etc/udev/rules.d/99-usb-auto-mount.rules
\cp /opt/Bunn/application/linuxSystemFiles/99-usb-serial.rules /etc/udev/rules.d/99-usb-serial.rules
\cp /opt/Bunn/application/linuxSystemFiles/70-persistent-net.rules /etc/udev/rules.d/70-persistent-net.rules

# reload udev rules
udevadm control --reload-rules
# reassign existing devices that meet criteria
udevadm trigger

# blacklist automatic configuration of usb interfaces allowing the above 70-persistent-net.rules to work with post boot hotplugs
#
# during boot the interface rename is successful because udevd runs before connman is launched
# but if the device is hotplugged while connman is running you'll see the following failure...
# udevd[3910]: Error changing net interface name usb0 to enx0242554e4e11: Device or resource busy
# udevd[3910]: could not rename interface '5' from 'usb0' to 'enx0242554e4e11': Device or resource busy
if [ ! -f /etc/connman/main.conf ]; then
  mkdir -p /etc/connman
  cat > /etc/connman/main.conf << EOF
[General]
NetworkInterfaceBlacklist=usb
EOF
  /etc/init.d/connman restart
fi

/opt/Bunn/application/bin/sshd-setup-key-authentication.sh

# tap display ssh setup...
#test -d /home/root/.ssh || mkdir /home/root/.ssh
#if [ ! -f /home/root/.ssh/id_rsa_tap_display ]; then
#  chmod 600 /opt/Bunn/application/bin/id_rsa_tap_display
#  ln -s /opt/Bunn/application/bin/id_rsa_tap_display /home/root/.ssh/id_rsa_tap_display
#fi
#if [ ! -f /home/root/.ssh/config ]; then
  # tap 1
#  echo 'Host 172.21.255.202' >> /home/root/.ssh/config
#  echo -e '\tUser root' >> /home/root/.ssh/config
#  echo -e '\tPreferredAuthentications publickey' >> /home/root/.ssh/config
#  echo -e '\tIdentityFile /home/root/.ssh/id_rsa_tap_display' >> /home/root/.ssh/config
  # tap 2
#  echo >> /home/root/.ssh/config
#  echo 'Host 172.22.255.202' >> /home/root/.ssh/config
#  echo -e '\tUser root' >> /home/root/.ssh/config
#  echo -e '\tPreferredAuthentications publickey' >> /home/root/.ssh/config
#  echo -e '\tIdentityFile /home/root/.ssh/id_rsa_tap_display' >> /home/root/.ssh/config
  # tap 3
#  echo >> /home/root/.ssh/config
#  echo 'Host 172.23.255.202' >> /home/root/.ssh/config
#  echo -e '\tUser root' >> /home/root/.ssh/config
#  echo -e '\tPreferredAuthentications publickey' >> /home/root/.ssh/config
#  echo -e '\tIdentityFile /home/root/.ssh/id_rsa_tap_display' >> /home/root/.ssh/config
#fi

if [ ! -f /etc/init.d/bunn ]; then
  ln -s /opt/Bunn/application/bin/initd.service /etc/init.d/bunn
fi

if [ ! -f /etc/init.d/bunn-main ]; then
  ln -s /opt/Bunn/application/bin/main-initd.service /etc/init.d/bunn-main
fi

if [ ! -d /usr/local/bin ]; then
  mkdir -p /usr/local/bin
fi
if [ ! -f /usr/local/bin/rsync ]; then
  ln -s /opt/Bunn/application/linuxSystemFiles/rsync /usr/local/bin/rsync
fi

# unexpected signals (ie. SIGSEGV) to the application can cause broken pipes, terminating logger instances with an unhandled SIGPIPE
# logger instances are launched below in forever loops, this prevents the application relaunch from hanging
#
# mkfifo(3)
# Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa.

if [ ! -p /var/run/bunn-stdout ]; then
  mkfifo /var/run/bunn-stdout
  /bin/sh -c "while true; do logger --tag bunn-stdout < /var/run/bunn-stdout; done" &
fi

if [ ! -p /var/run/bunn-stderr ]; then
  mkfifo /var/run/bunn-stderr
  /bin/sh -c "while true; do logger --tag bunn-stderr < /var/run/bunn-stderr; done" &
fi

# prevent pr_info "alloc_contig_range: [%lx, %lx) PFNs busy" spew on the console
# https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/mm/page_alloc.c
# KERN_INFO = 6
echo 6 > /proc/sys/kernel/printk

psplash-write "PROGRESS 99"

ulimit -c unlimited
cd /opt/Bunn/application/bin
while true; do
  ./bunn-main-app $1 1>/var/run/bunn-stdout 2>/var/run/bunn-stderr
  code=$?
  if [ $code -ne 143 ] && [ $code -ne 137 ]; then # SIGTERM && SIGKILL
    logger --tag bunn-unexpected-exit $code
    if [ $code -eq 139 ] || [ $code -eq 134 ]; then # SIGSEGV || SIGABRT
      killall -9 WatchDawg.sh
      /opt/Bunn/application/bin/progress-bar-loop.sh &
      pid=$!
      date >> /opt/Bunn/nvm/logs/backtraces
      gdb -se bunn-main-app -c core -batch -ex "bt" | tee --append /opt/Bunn/nvm/logs/backtraces | logger --tag bunn-backtrace
      echo >> /opt/Bunn/nvm/logs/backtraces
      kill $pid
    fi
  fi

  pgrep WatchDawg.sh
  if [ $? -eq 0 ]; then
    exit 0 # let WatchDawg restart application
  fi
done
