#!/bin/bash
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL

# Decide the path for live media.
# casper 1.77+debian-7 uses /live_media, 1.110 uses /cdrom
# live-initramfs uses /live/image.
if [ -f "/cdrom/casper/filesystem.squashfs" ]; then
  LIVE_MEDIA="cdrom"
elif [ -f "/live_media/casper/filesystem.squashfs" ]; then
  LIVE_MEDIA="live_media"
elif [ -f "/live/image/filesystem.squashfs" ]; then
  LIVE_MEDIA="live/image"
else
  echo "///WARNING/// filesystem.squashfs not found! No idea where is LIVE_MEDIA!!!"
fi

# Prepare drbl/clonezilla runtime programs and dir
echo "Preparing Clonezilla program..."
tar -xzf /$LIVE_MEDIA/pkg/opt_drbl.tgz -C /
if [ -e /$LIVE_MEDIA/pkg/custom-ocs ]; then
  # We do not put custom-ocs in /opt/drbl/sbin/, we put it in /opt/local/sbin/ so that when we use clonezilla live to create a custom clonezilla live, it won't be put in the custom clonezilla live. It should be put by ocs-iso, not in the tarball.
  mkdir -p /opt/local/sbin/
  cp -f /$LIVE_MEDIA/pkg/custom-ocs /opt/local/sbin/
  chmod 755 /opt/local/sbin/custom-ocs
fi
cp -a /$LIVE_MEDIA/etc/ocs /etc/
mkdir -p /opt/drbl/lib/; ln -fs /$LIVE_MEDIA/pkg/unifont.bgf /opt/drbl/lib/unifont.bgf

# Try to parse the kernel param
# 1. ocs_live_keymap
# 2. ocs_lang
ker_param_chklist="ocs_live_keymap ocs_lang"
parse_tmp="$(mktemp /tmp/cmdtmp.XXXXXX)"
for ik in $ker_param_chklist; do
  # the parameter maybe like: ocs_lang=en or ocs_lang="en"
  grep -oE "$ik=[\"]*.*[\"]*[[:space:]]+" /proc/cmdline > $parse_tmp
  # now we can get the variable $ocs_live_keymap or $ocs_lang
  . $parse_tmp
done
[ -f "$parse_tmp" ] && rm -f $parse_tmp

# tune the param in /etc/ocs-live.conf
for ik in $ker_param_chklist; do
  eval real_var=\$$ik
  if [ -n "$real_var" ]; then
    perl -pi -e "s/^.*$ik=.*/$ik=$real_var/g" /etc/ocs/ocs-live.conf
  fi
done
