#!/usr/bin/env bash

TARGET=${1}
ACTION=${2}

if [ ${ACTION} == "enable" ]; then
  # grub2 EFI fix for Z37xx
  tablet_z37xx=`cat /var/log/syslog | grep "CPU" | grep "Z37"`
  if [ "`mount | grep "boot/efi"`" != "" ]; then
  install_32bit=${ACTION}
  fi
  if [ "${tablet_z37xx}" != "" ] || [ "$install_32bit" == "enable" ]; then
    if [ -d ${TARGET}/opt/baytrail ]; then
      cp -rf ${TARGET}/etc/default/grub ${TARGET}/etc/default/grub-orig
      chroot ${TARGET} /usr/bin/dpkg -P grub-efi
      chroot ${TARGET} /usr/bin/dpkg -P grub-efi-amd64
      chroot ${TARGET} /usr/bin/dpkg -P grub-efi-amd64-bin
      echo "ucf	ucf/changeprompt_threeway	select	install_new" > ${TARGET}/opt/grub_selections
      echo "ucf	ucf/changeprompt	select	install_new" >> ${TARGET}/opt/grub_selections

      chroot ${TARGET} /usr/bin/debconf-set-selections /opt/grub_selections
      if [ -f ${TARGET}/opt/grub_selections ]; then
        rm ${TARGET}/opt/grub_selections
      fi
      mv -f ${TARGET}/etc/default/grub-orig ${TARGET}/etc/default/grub
      for i in `ls ${TARGET}/opt/baytrail`
        do
        if [ "$tablet_z37xx" != "" ]; then
          chroot ${TARGET} /usr/bin/dpkg -i /opt/baytrail/$i
        else
          if [ `echo $i | grep "grub"` ]; then
            chroot ${TARGET} /usr/bin/dpkg -i /opt/baytrail/$i
          fi
        fi
        done
    fi
    in-target sh -c "debconf-apt-progress --no-progress --logstderr -- \
      apt-get -f -y install"

      hardware_name=`cat /var/log/syslog | grep "DMI" | grep "ASUS"`
      if [ "${hardware_name}" != "" ]; then
        if  [ -f ${TARGET}/etc/default/grub ]; then
          if [ -z "`cat ${TARGET}/etc/default/grub | grep "i915.force_backlight_pmic=1"`" ]; then
            sed -i -e 's/GRUB_CMDLINE_LINUX=\"reboot=pci\,force /GRUB_CMDLINE_LINUX=\"reboot=pci\,force i915.force_backlight_pmic=1 /g' ${TARGET}/etc/default/grub
          fi
        fi
        chroot ${TARGET} /usr/sbin/update-grub
      fi
  fi
  if [ -d ${TARGET}/opt/baytrail ]; then
      chroot ${TARGET} /usr/bin/dpkg -P baytrail-install
  fi
fi

if [ "${ACTION}" == "status" ]; then
  exit 1
fi
