#!/bin/sh
#
# control linbo_gui: gui_ctl <disable|enable|restore>
# thomas@linuxmuster.net
# 20250912
#

# intercept nogui parameter
[ -n "$NOGUI" ] && echo "Linbo was started with \"nogui\". Doing nothing." && exit

# test start.conf
[ -s /start.conf ] || exit 1

# get environment
source /usr/share/linbo/shell_functions
echo "### $timestamp $(basename "$0") $@ ###"

# test gui
gui_ps="$(ps w | grep linbo_gui | grep -v grep | awk '{print $1, $5}')"
gui_pid="$(echo "$gui_ps" | awk '{print $1}')"

backup_start_conf() {
  # only backup if there is not backup yet
  if test ! -f "/start.conf.bak"; then
    cp /start.conf /start.conf.bak
  fi
}

disable() {
  echo "Disabling linbo_gui."
  backup_start_conf
  if grep -qi ^GuiDisabled /start.conf; then
    sed -i 's|^[Gg][Uu][Ii][Dd][Ii][Ss][Aa][Bb][Ll][Ee][Dd].*|GuiDisabled = yes|' /start.conf || exit 1
  else
    sed -i 's|^\[[Ll][Ii][Nn][Bb][Oo]\]|\[LINBO\]\nGuiDisabled = yes|' /start.conf || exit 1
  fi
}

enable() {
  echo "Enabling linbo_gui."
  backup_start_conf
  if grep -qi ^GuiDisabled /start.conf; then
    sed -i 's|^[Gg][Uu][Ii][Dd][Ii][Ss][Aa][Bb][Ll][Ee][Dd].*|GuiDisabled = no|' /start.conf || exit 1
  else
    sed -i 's|^\[[Ll][Ii][Nn][Bb][Oo]\]|\[LINBO\]\nGuiDisabled = no|' /start.conf || exit 1
  fi
}

# do commands
case "$1" in
  disable) disable ; shift ;;
  enable) enable ; shift ;;
  restore)
    echo "Restoring gui."
    if [ -s /start.conf.bak ]; then
      mv /start.conf.bak /start.conf || exit 1
    else
      exit 1
    fi
    shift
    ;;

  *) exit 1 ;;
esac

# get onboot option
[ "$1" = "onboot" ] && onboot="yes"

# split changed start.conf
[ -z "$onboot" ] && linbo_split_startconf

if [ -n "$gui_pid" -a -z "$onboot" ]; then
  kill "$gui_pid" || exit 1
fi
