#!/bin/sh
#
# Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# If in auto-install mode, replace default lightdm.conf and launch installer.

prereqs() {
  echo "$PREREQ"
}

case $1 in
  prereqs)
    prereqs
    exit 0
    ;;
esac

# Modify lightdm config file.
generate_lightdm_conf() {
  local CONF_FILE="$1"
  local HELPER_FILE="$2"
  cat > "${CONF_FILE}" <<EOF
[Seat:*]
greeter-setup-script=$HELPER_FILE
EOF
}

generate_installer_helper() {
  local HELPER_FILE="$1"
  local LOCALE="$2"
  local CONF_FILE="$3"
  local LOG_FILE="$4"

  cat > "${HELPER_FILE}" <<EOF
#!/bin/sh
##gconftool-2 --set --type=bool /apps/gksu/display-no-pass-info false || true
/usr/bin/deepin-installer --conf "${CONF_FILE}" --log "${LOG_FILE}" --auto-install
EOF
}

# Read kernel parameter and set global variables.
parse_cmdline() {
  for x in $(cat /proc/cmdline); do
    case $x in
      auto-deepin-installer)
        auto_mode=true
        ;;
      install-path=*)
        install_path="${x#install-path=}"
        ;;
      deepin-installer/locale=*)
        locale=${x#deepin-installer/locale=}
        ;;
      esac
  done
}

config_auto_mode() {
  local installer_conf installer_log installer_helper
  if [ x"$auto_mode" = xtrue ]; then
    #fix install_path
    #if use boot config, iso mount on /lib/live/mount/findiso
    iso_root=/lib/live/mount/findiso
    install_path=$iso_root/$install_path

    lang=$(echo $locale | awk -F '.' '{print $1}')
    # set locale
    echo $locale
    printf 'LANG="%s"\nLANGUAGE="%s"\n' "$locale" "$lang" > /etc/default/locale
    printf 'LANG="%s"\nLANGUAGE="%s"\n' "$locale" "$lang" >> /etc/environment
      sed -i "s/# \(en_US\.UTF-8.*$\)/\1/g" /etc/locale.gen
      sed -i "s/# \(${locale}.*$\)/\1/g" /etc/locale.gen
    /usr/sbin/locale-gen || true

    installer_conf=$install_path/install/deepin-installer.conf
    installer_log=$install_path/install/deepin-installer.log
    installer_helper=/usr/lib/deepin-installer-helper
    generate_installer_helper $installer_helper $locale $installer_conf $installer_log
    generate_lightdm_conf /etc/lightdm/lightdm.conf $installer_helper

    chmod +x $installer_helper
  fi
}

parse_cmdline
config_auto_mode
