#!/bin/sh
set -e

GRUB_CONF=/boot/grub/menu.lst
GRUB2_CONF=/etc/default/grub
UBOOT_CONF=/etc/u-boot-menu/conf.d/selinux.conf

if [ "$1" != "disable" ]; then
  echo "Activating SE Linux"
  if [ -e $GRUB_CONF ]; then
    if ! grep -q selinux $GRUB_CONF ; then
      sed -i "s/\(^# kopt=.*$\)/\1 security=selinux/" $GRUB_CONF
      update-grub
    fi
  fi
  if [ -e $GRUB2_CONF ]; then
    sed -i -e "s/ \?selinux=1//g" -e "s/ \?security=selinux//g" -e "s/\(^GRUB_CMDLINE_LINUX=.*\)\"$/\1 security=selinux\"/" $GRUB2_CONF
    update-grub
  fi
  if [ -d $(dirname $UBOOT_CONF) ]; then
    echo 'U_BOOT_PARAMETERS="security=selinux $U_BOOT_PARAMETERS"' > $UBOOT_CONF
    u-boot-update
  fi
  touch /.autorelabel
  echo "SE Linux is activated.  You may need to reboot now."
else
  echo "Deactivating SE Linux"
  # we assume that EPERM on /sys/fs/selinux/enforce means that
  # all subsequent operations get EPERM
  if grep -q 1 /sys/fs/selinux/enforce 2> /dev/null ; then
    echo "You should be in permissive mode to disable SE Linux."
    echo "Run \"setenforce 0\" first if you really want to do this."
    exit 1
  fi

  if [ -e $GRUB_CONF ]; then
    sed -i -e "s/ selinux=1//" -e "s/ security=selinux//" $GRUB_CONF
  fi
  if [ -e $GRUB2_CONF ]; then
    if grep -q selinux $GRUB2_CONF 2> /dev/null ; then
      sed -i -e "s/ \?selinux=1//" -e "s/ \?security=selinux//" $GRUB2_CONF
      update-grub
    fi
  fi
  if [ -d $(dirname $UBOOT_CONF) ]; then
    rm -f $UBOOT_CONF
    u-boot-update
  fi
  rm -f /.autorelabel
  echo "SE Linux is deactivated.  You may need to reboot now."
fi
