#!/bin/sh
#
# dcp2000/base-files package post installation script
#

. ${PKGLIB_SH}

# get_md5sum(string path_file)
# Get the md5sum of a file
# Return code: 0 on success, 1 on failure
#   Eg: get_md5sum /doremi/bin/odeticsd.out
#
get_md5sum(){
  local PATH_FILE="$1"
  local MD5SUM=""

  if ! test -f "${PATH_FILE}"; then
    return 1
  elif ! MD5SUM="$(md5sum "${PATH_FILE}" 2> /dev/null)"; then
    return 1
  elif [ "${MD5SUM}" == "" ]; then
    return 1
  else
    echo "${MD5SUM}" | awk '{print $1}'
  fi

  return 0
}

#
# update_release_md5()
# Updates a file md5sum
#
update_release_md5(){
  local BINARY="$1"
  local RELEASE_MD5="/doremi/etc/release.md5"

  if ! test -f "${RELEASE_MD5}"; then
    return 1
  elif ! test -f "${BINARY}"; then
    return 1
  elif grep -q " ${BINARY}$" "${RELEASE_MD5}"; then
    local oldmd5=$(grep " ${BINARY}$" "${RELEASE_MD5}" | cut -d ' ' -f1 | tr -d [:space:])
    local newmd5=$(md5sum "${BINARY}" | cut -d ' ' -f1 | tr -d [:space:])

    if [ "${oldmd5}" == "" ] || [ "${newmd5}" == "" ] ; then
      return 1
    elif ! sed -i -e "s/${oldmd5}/${newmd5}/" "${RELEASE_MD5}"; then
      return 1
    fi
  elif ! md5sum "${BINARY}" >> "${RELEASE_MD5}"; then
    return 1
  fi

  return 0
}

#
# update_apache2()
# Update the apache2 configuration and install files
#
update_apache2() {
  if [ -f /etc/php5/apache2/php.ini ] ; then
    if grep -q 'display_errors = On' /etc/php5/apache2/php.ini; then
      sed -i -e 's/^display_errors = On$/display_errors = Off/g' /etc/php5/apache2/php.ini
    fi
  fi

  if [ -f /etc/apache2/mods-enabled/php5.conf ] ; then
    if ! grep -q .html /etc/apache2/mods-enabled/php5.conf; then
      sed -i -e 's/AddType application\/x-httpd-php .php .phtml .php3$/AddType application\/x-httpd-php .php .phtml .php3 .html/g' /etc/apache2/mods-enabled/php5.conf
    fi
  fi

  if test -f /etc/apache2/conf.d/doremi.conf; then
    rm -f /etc/apache2/conf.d/doremi.conf > /dev/null 2>&1
  fi

  if test -r /etc/apache2/httpd.conf; then
    if grep -q doremi /etc/apache2/httpd.conf; then
      rm -f /etc/apache2/httpd.conf > /dev/null 2>&1
      touch /etc/apache2/httpd.conf
      chown root.root /etc/apache2/httpd.conf
      chmod 0644 /etc/apache2/httpd.conf
    fi
  fi

  install -o root -g root -m 0644 -D    "/tmp/etc/apache2/apache2.conf"             "/etc/apache2/apache2.conf"
  ln -sf                                "../mods-available/proxy.conf"              "/etc/apache2/mods-enabled/proxy.conf"
  ln -sf                                "../mods-available/proxy.load"              "/etc/apache2/mods-enabled/proxy.load"
  ln -sf                                "../mods-available/proxy_http.load"         "/etc/apache2/mods-enabled/proxy_http.load"

  install -o root -g root -m 0644 -D    "/tmp/etc/apache2/sites-available/drm-aux"  "/etc/apache2/sites-available/drm-aux"
  update_release_md5                    "/etc/apache2/sites-available/drm-aux"
  ln -sf                                "../sites-available/drm-aux"                "/etc/apache2/sites-enabled/042-drm-aux"

  install -o root -g root -m 0644 -D    "/tmp/etc/apache2/sites-available/drm-rpls" "/etc/apache2/sites-available/drm-rpls"
  update_release_md5                    "/etc/apache2/sites-available/drm-rpls"
  ln -sf                                "../sites-available/drm-rpls"               "/etc/apache2/sites-enabled/042-drm-rpls"

  return 0
}

#
# update_mdadm()
# Update mdadm version
#
update_mdadm() {
  ln -sf  "mdadm-2.6.7.2"               "/sbin/mdadm"

  return 0
}

update_apache_module_if_needed(){
  # Proceed with file installation if, and only if, the existing file on system is the original one.
  # Reason: we don't know what can be the effect of this file update in case the apache2 binary version is not exactly
  # the one installed on Goldmaster (it can happens if the administrator does a apt-get upgrade for example).
  local GOLDMASTER_MODULE_MD5SUM="32ef4690577bee273f18da9bef2f3c6d"
  local SYSTEM_MODULE_MD5SUM="$(get_md5sum /usr/lib/apache2/modules/mod_proxy.so)"
  local PACKAGE_MODULE_MD5SUM="$(get_md5sum /tmp/usr/lib/apache2/modules/mod_proxy.so)"

  if [ "${SYSTEM_MODULE_MD5SUM}" != "${GOLDMASTER_MODULE_MD5SUM}" ]; then
    # If it is not the module of this package, log a warning.
    if [ "${SYSTEM_MODULE_MD5SUM}" != "${PACKAGE_MODULE_MD5SUM}" ]; then
      echo "WARNING: Apache2 module 'mod_proxy.so' has not been updated (it is not the one installed on Gold Master)."
    fi

    return 0
  fi

  # Ok, we can install
  install -o root -g root -m 0644 -D "/tmp/usr/lib/apache2/modules/mod_proxy.so" "/usr/lib/apache2/modules/mod_proxy.so"
  update_release_md5                 "/usr/lib/apache2/modules/mod_proxy.so"

  return 0
}

function replace_x11_field() {
	SECTION="$1"
	FIELD="$2"
	VALUE="$3"
	FILENAME="$4"
	sed -i -r  "/^Section \"${SECTION}\"/,/^EndSection/ s/(${FIELD}.*\")[^\"]*\"/\\1${VALUE}\"/" ${FILENAME} \
		|| die "WARNING: failed to update xorg.conf with correct display settings."
}

if ! DEBVER=$(get_debian_version); then
	die "Critical error: Unknown debian version."
fi

GRUB_MENU="/boot/grub/menu.lst"
GRUB_BCKP="/boot/grub/.menu.lst.$$"
# Patch Grub file (task #3081)
if grep -q bigphysarea $GRUB_MENU; then
	MemTotal=`cat /proc/meminfo | grep MemTotal | cut -d : -f 2  | tr -d [:alpha:] | tr -d [:space:]`
	if [ ${MemTotal} -ge 1034436 ]; then
		# 2GB setup
		mem="1300M"
		memmap="748M\$1300M"
        else
		# 1GB setup
		mem="700M"
		memmap="324M\$700M"
        fi
        cp -f $GRUB_MENU $GRUB_BCKP
        sed s/"bigphysarea=76800"/"mem=${mem} memmap=${memmap} vmalloc=320M"/g -i $GRUB_MENU
        if grep -q bigphysarea $GRUB_MENU; then
		mv -f $GRUB_BCKP $GRUB_MENU
		# TODO: die()
                echo "Could not patch grub configuration file. Please call the technical support."
                exit 1
        fi
        if grep -q "imb=0x88100000" $GRUB_MENU; then
                sed s/"imb=0x88100000,0x881fffff"/"imb=0xd0200000,0xd02fffff"/g -i $GRUB_MENU
                if grep -q "imb=0x0x88100000" $GRUB_MENU; then
			mv -f $GRUB_BCKP $GRUB_MENU
                        echo "Could not patch grub configuration file. Please call the technical support."
                        exit 1
                fi
        fi

fi

# Remove workaround for Debian 3 (Jira DCPLYR-3118)
if [ ${DEBVER} -eq 3 ]; then
	if grep sysfs.deprecated ${GRUB_MENU}; then
		sed -i -e 's@sysfs.deprecated=1@@g' ${GRUB_MENU}
	fi
fi

# Create symbolic link file
ln -sf libicudata.so                       /usr/lib/libicudata.so.28.0
ln -sf libicudata.so.28                    /usr/lib/libicudata.so.28.0
ln -sf libicui18n.so                       /usr/lib/libicui18n.so.28.0
ln -sf libicui18n.so.28                    /usr/lib/libicui18n.so.28.0
ln -sf libicuio.so                         /usr/lib/libicuio.so.28.0
ln -sf libicuio.so.28                      /usr/lib/libicuio.so.28.0
ln -sf libicuuc.so                         /usr/lib/libicuuc.so.28.0
ln -sf libicuuc.so.28                      /usr/lib/libicuuc.so.28.0

ln -sf ../init.d/update.init 		   /doremi/etc/rcS.d/00_update
ln -sf ../init.d/drmise1d.init     	   /doremi/etc/hotplug.d/50_drmise1d
ln -sf ../init.d/drmcssd.init      	   /doremi/etc/hotplug.d/50_drmcssd
ln -sf ../init.d/force_3d_mode.init        /doremi/etc/hotplug.d/99_force_3d_mode

#delete obsolete force_3d_444_enable package (replaced by the force_3d_mode.init script)
rm -f /doremi/etc/hotplug.d/99_force_3d_444_enabled
rm -f /doremi/etc/init.d/force_3d_444_enabled.init

# System integration
ln -sf ../init.d/doremi-rcS.d              /etc/rcS.d/S99doremi-rcS.d
ln -sf ../init.d/doremi-rc.d               /etc/rc0.d/K10doremi-rc.d
ln -sf ../init.d/doremi-rc.d               /etc/rc2.d/S99doremi-rc.d
ln -sf ../init.d/doremi-rc.d               /etc/rc6.d/K10doremi-rc.d
ln -sf ../init.d/doremi-hotplug.d          /etc/rc0.d/K15doremi-hotplug.d
ln -sf ../init.d/doremi-hotplug.d          /etc/rc6.d/K15doremi-hotplug.d

for level in 2 3 5; do
	ln -sf ../init.d/smd.init          /etc/rc${level}.d/S12smd
	ln -sf ../init.d/pre-dcp2000.init  /etc/rc${level}.d/S13pre-dcp2000
done

for level in 0 6; do
	ln -sf ../init.d/smd.init          /etc/rc${level}.d/K99smd
done

# Compat
ln -sf /doremi/etc/init.d/update.init      /etc/init.d/update.init

# lib xerces for dolby atmos
ln -sf /usr/lib/libxerces-c.so.26.0        /usr/lib/libxerces-c.so.26

# apache2
DEBIAN_VERSION=$(cat /etc/debian_version)
case "$DEBIAN_VERSION" in
  4.0)
    # etch
    update_apache_module_if_needed
    update_apache2
    update_mdadm
    ;;

  3.0)
    # sarge
    install -m 0644 -o root -g root -D "/tmp/debian/sarge/etc/X11/Xsession.d/01xfree86-check_default_language"  "/etc/X11/Xsession.d/01xfree86-check_default_language"
    ;;

  *)
    ;;
esac

install -m 0755 -o root -g root -D "/tmp/usr/bin/zip"                                           "/usr/bin/zip"
install -m 0755 -o root -g root -D "/tmp/usr/bin/unzip"                                         "/usr/bin/unzip"
install -m 0644 -o root -g root -D "/tmp/etc/fonts/local.conf"                                  "/etc/fonts/local.conf"
install -m 0644 -o root -g root -D "/tmp/etc/init.d/snmpd"                                      "/etc/init.d/snmpd"
if [ -f /etc/sensors3.conf ]; then
  sed -i -e "s/^[^#].*ignore fan4/#&/" /etc/sensors3.conf
else
  install -m 0644 -o root -g root -D "/tmp/etc/sensors3.conf"       "/etc/sensors3.conf"
fi
install -m 0644 -o root -g root -D "/tmp/etc/X11/Xsession.d/01xfree86-check_default_language"   "/etc/X11/Xsession.d/01xfree86-check_default_language"
install -m 0644 -o root -g root -D "/tmp/doremi/etc/ntpservers.sample"                          "/doremi/etc/ntpservers.sample"

test -f /var/etc/issue                          || cp -f  /etc/issue                    /var/etc/issue
test -f /var/etc/issue.net                      || cp -f  /etc/issue.net                /var/etc/issue.net
test -L /etc/issue                              || ln -sf /var/etc/issue                /etc/issue
test -L /etc/issue.net                          || ln -sf /var/etc/issue.net            /etc/issue.net

# Update Xorg.conf display configuration based on underlying DCP2000 motherboard.
# Remember: X10 uses VESA, while others use ATI.
# (Jira DCPLYR-2850)
if test -r /etc/X11/xorg.conf; then
	XORG_CONF="/etc/X11/xorg.conf"
	XORG_CONF_BAK="/etc/X11/xorg.conf.bak"

	# Do we have an ATI card? (X7, etc..)
	if lspci -n -d "1002:*" | grep -q "1002:"; then
	       if grep "Driver" ${XORG_CONF} | grep -q vesa; then
			# VESA to ATI
			print_msg "Updating X11 config to use ATI display driver (Supermicro X7)"
			cp ${XORG_CONF} ${XORG_CONF_BAK}
			replace_x11_field Device Identifier "ATI Technologies, Inc. Rage 128 PF PRO AGP 4x TMDS" ${XORG_CONF_BAK}
			replace_x11_field Device Driver "ati" ${XORG_CONF_BAK}
			replace_x11_field Monitor HorizSync "30-60" ${XORG_CONF_BAK}
			replace_x11_field Screen Device "ATI Technologies, Inc. Rage 128 PF PRO AGP 4x TMDS" ${XORG_CONF_BAK}
			cp ${XORG_CONF_BAK} ${XORG_CONF}
			print_success
	       fi

	else
	       if grep "Driver" ${XORG_CONF} | grep -q ati; then
			# ATI to VESA
			print_msg "Updating X11 config to use VESA display driver (Supermicro X10)"
			cp ${XORG_CONF} ${XORG_CONF_BAK}
			replace_x11_field Device Identifier "Generic VESA" ${XORG_CONF_BAK}
			replace_x11_field Device Driver "vesa" ${XORG_CONF_BAK}
			replace_x11_field Monitor HorizSync "28-82" ${XORG_CONF_BAK}
			replace_x11_field Screen Device "Generic VESA" ${XORG_CONF_BAK}
			cp ${XORG_CONF_BAK} ${XORG_CONF}
			print_success
	       fi
	fi
fi

