#!/bin/bash
APPARMOR_INIT=/etc/init.d/apparmor
GLOBAL_MYSQL_FILE=/etc/apparmor.d/usr.sbin.mysqld
LOCAL_MYSQL_FILE=/etc/apparmor.d/local/usr.sbin.mysqld
FTMP=`mktemp /tmp/tmp.XXXXXX`

restart_apparmor() 
{
  #apparmor config file may exists and apparmor itself not
  if [ -f $APPARMOR_INIT ]
  then
    if which invoke-rc.d >/dev/null 2>&1; then
       invoke-rc.d apparmor restart
    else
      /etc/init.d/apparmor restart
    fi    
  else
    echo it seems apparmor is not installed, restarting skipped
  fi
}

if [ -f "$GLOBAL_MYSQL_FILE" ] 
then
  grep -v "@{HOME}/.config/cqrlog/database/" $GLOBAL_MYSQL_FILE >> $FTMP
  cat $FTMP > $GLOBAL_MYSQL_FILE
  echo ""
  echo Changes removed from $GLOBAL_MYSQL_FILE
  echo ""  
  
  if `cat $LOCAL_MYSQL_FILE | grep -q -E '\@\{HOME\}\/\.config\/cqrlog\/database\/\*\*\ rwk\,'`
  then
    if ! grep -q "@{HOME}/.config/cqrlog/database/  r," "$LOCAL_MYSQL_FILE"; then
      echo "@{HOME}/.config/cqrlog/database/  r," >> $LOCAL_MYSQL_FILE
      echo File $LOCAL_MYSQL_FILE was modified, restarting apparmor
      echo "" 
      restart_apparmor
      echo ""
    else
      echo ""
      echo File $LOCAL_MYSQL_FILE was already modified, no changes needed
      echo ""   
    fi   
  else
    echo "@{HOME}/.config/cqrlog/database/  r," >> $LOCAL_MYSQL_FILE
    echo "@{HOME}/.config/cqrlog/database/** rwk," >> $LOCAL_MYSQL_FILE
    echo ""
    echo File $LOCAL_MYSQL_FILE was modified, restarting apparmor
    echo "" 
    restart_apparmor
    echo ""
  fi
fi
rm $FTMP

