#! /bin/bash

set -e

if [ ! -f /etc/laptop-mode/laptop-mode.conf -o ! -f /usr/sbin/laptop_mode ] ; then
  echo Laptop mode does not seem to be installed.
  exit 1
fi

. /usr/sbin/laptop_mode defaults
. /etc/laptop-mode/laptop-mode.conf

if [ ! -f $SYSLOG_CONF ] ; then
  echo Syslog configuration file \"$SYSLOG_CONF\" not found. 
  echo Please configure the correct path in /etc/laptop-mode/laptop-mode.conf.
  exit 1
fi

echo This script helps you to set up separate syslog.conf files for the
echo various modes a laptop can be in. Switching between the configurations
echo is managed by the Laptop Mode Tools.
echo

if [ "`readlink $SYSLOG_CONF`" != "" ] ; then
  echo $SYSLOG_CONF already seems to be symlinked. Either lm-syslog-setup
  echo has already been called, or some other program manages the syslog.conf
  echo symlink. This script will not continue, for safety reasons.
  exit 1
fi

echo Creating config files:
echo
echo -n AC power, laptop mode off: $AC_SYSLOG_WITHOUT_LM
if [ -f "$AC_SYSLOG_WITHOUT_LM" ] ; then
  echo " (exists)"
else
  if ( cp -a "$SYSLOG_CONF" "$AC_SYSLOG_WITHOUT_LM" ) ; then
    echo " (created)"
  else
    echo " (creation failed, exiting)"
    exit 1
  fi
fi
echo -n AC power, laptop mode on: $AC_SYSLOG_WITH_LM
if [ -f "$AC_SYSLOG_WITH_LM" ] ; then
  echo " (exists)"
else
  if ( cp -a "$SYSLOG_CONF" "$AC_SYSLOG_WITH_LM" ) ; then
    echo " (created)"
  else
    echo " (creation failed, exiting)"
    exit 1
  fi
fi
echo -n Battery power: $BATT_SYSLOG
if [ -f "$BATT_SYSLOG" ] ; then
  echo " (exists)"
else
  if ( cp -a "$SYSLOG_CONF" "$BATT_SYSLOG" ) ; then
    echo " (created)"
  else
    echo " (creation failed, exiting)"
    exit 1
  fi
fi
echo
while [ "$DO_ENABLE" != "y" -a "$DO_ENABLE" != "n" ] ; do
  echo -n "Do you wish to enable the split configuration now? (y/n) "
  read DO_ENABLE
done
if [ "$DO_ENABLE" == "y" ] ; then
  if ( ! sed -i /etc/laptop-mode/laptop-mode.conf -e "s/DO_SYSLOG=0/DO_SYSLOG=1/" || ! grep DO_SYSLOG=1 /etc/laptop-mode/laptop-mode.conf ) ; then
    echo Enabling the split configuration failed.
    exit 1
  else
    echo Enabling the split configuration succeeded.
    echo Restarting laptop mode to activate changes.
    /usr/sbin/laptop_mode auto force
  fi
fi
