#!/bin/bash

set -e
set -o pipefail

export info_version_string=
export mate_data_add_string=
export os_version_name=
export sign_position=

mkdir -p /var/log/installer

# 拷贝配置文件
do_copy_config() {

  # sp1 使用 automatic
  if grep -q automatic /proc/cmdline; then
    if grep -q "url=" /proc/cmdline; then
        if [[ -f /cdrom/ky-installer.cfg ]]; then
                cp /cdrom/ky-installer.cfg /tmp
        fi
        if grep -q "cfg=" /proc/cmdline; then
                cmd_cfg=$(cat /proc/cmdline)
                url_ip=$(echo ${cmd_cfg##*url=}| awk '{print $1}')
                url_ip=${url_ip%/*}
                cfg=$(echo ${cmd_cfg##*cfg=}| awk '{print $1}')
                wget ${url_ip}/${cfg} -O /tmp/ky-installer.cfg
        fi
    else
        if grep -q "cfg=" /proc/cmdline; then
                cmd_cfg=$(cat /proc/cmdline)
                cfg=$(echo ${cmd_cfg##*cfg=}| awk '{print $1}')
                cp /cdrom/${cfg}  /tmp/ky-installer.cfg
        else
                if [[ -f /cdrom/ky-installer.cfg ]]; then
                        cp /cdrom/ky-installer.cfg /tmp
		elif [[ -f /cdrom/kyple-installer.cfg ]]; then
			cp /cdrom/kyple-installer.cfg /tmp/ky-installer.cfg
                else
                        echo "ky-installer.cfg does not exist"
                        echo "您现在用的是自动安装流程，请将ky-installer.cfg放到iso根目录下"
                        exit 1
                fi

        fi
    fi
  # 990/9A0 使用此设置，ple-mode 审核模式，test-mode 全自动安装模式
  elif grep -qE 'ple-mode|test-mode' /proc/cmdline; then
    [[ -f /cdrom/kyple-installer.cfg ]] && cp /cdrom/kyple-installer.cfg /tmp/ky-installer.cfg
  else
    cp /usr/share/kylin-os-installer/ky-installer.cfg /tmp
  fi
  echo "ky-installer.cfg is ok"
}

do_copy_config >/var/log/installer/kylin-os-installer.log

# 使用绝对路径，方便在 /target 中加载
cp utils /tmp
. /tmp/utils

if grep -q automatic /proc/cmdline; then
        data_unformat=$(get_value data-unformat)
        if [[ "${data_unformat}" == "true" ]]; then
                save_disk=$(get_value devpath)
                if ! grep -q "save-data=${save_disk}" /var/log/installer/os-prober.log; then
                        echo "您选择了保留用户数据安装，但机器系统不满足保留用户数据要求，不能进行保留用户数据安装" >>/var/log/installer/kylin-os-installer.log
                        exit 1
                fi
        fi
fi

# 运行 prepare 脚本
do_prepare() {
  mkdir -p /var/log/installer

  if [[ -d /cdrom/hooks/prepare ]]; then
    run_scripts_hooks /cdrom/hooks/prepare
  fi
  hooks=$(get_value hooks)
  if [[ -n $hooks ]]; then
#  if grep -q "hooks=" /proc/cmdline; then
    if grep -q "url=" /proc/cmdline; then
            cmd_cfg=$(cat /proc/cmdline)
            url_ip=$(echo ${cmd_cfg##*url=}| awk '{print $1}')
            url_ip=${url_ip%/*}
#            hooks=$(echo ${cmd_cfg##*hooks=}| awk '{print $1}')
            wget -P/tmp ${url_ip}/${hooks}
            tar -xf /tmp/${hooks} -C /tmp/
    fi
  fi
  
  if [[ -d /tmp/hooks/prepare ]]; then
    run_scripts_hooks /tmp/hooks/prepare
  fi
  
  run_scripts_dir prepare

}

# 运行 in_chroot 脚本
do_run_target() {
  new_sysroot_dir=$(get_value new-root)
  mkdir -p $new_sysroot_dir/${IN_TARGET}
  cp utils /tmp/ky-installer.cfg $new_sysroot_dir/tmp
  cp -rf k.sh in_chroot $new_sysroot_dir/${IN_TARGET}
  
  if [[ -d /tmp/hooks/in_chroot ]]; then
     cp -r /tmp/hooks/in_chroot $new_sysroot_dir/tmp
  fi

  chroot $new_sysroot_dir bash ${IN_TARGET}/k.sh >>${LOG_FILE} 2>&1
}

# 运行 after 脚本
do_after() {
  run_scripts_dir after

  if [[ -d /cdrom/hooks/after ]]; then
    run_scripts_hooks /cdrom/hooks/after
  fi

  if [[ -d /tmp/hooks/after ]]; then
    run_scripts_hooks /tmp/hooks/after
  fi
}

# 执行 post 脚本
do_cdrom_post_actions() {
  new_sysroot_dir=$(get_value new-root)
  if [[ -f /cdrom/.kylin-post-actions ]] && [[ "${is_ghost}" != "true" ]]; then
    cp /cdrom/.kylin-post-actions $new_sysroot_dir/${IN_TARGET}
    chroot $new_sysroot_dir bash ${IN_TARGET}/.kylin-post-actions >>${LOG_FILE} 2>&1
  fi

  if [[ -f /cdrom/.kylin-post-actions-nochroot ]] && [[ "${is_ghost}" != "true" ]]; then
    bash /cdrom/.kylin-post-actions-nochroot >>${LOG_FILE} 2>&1
  fi
}

# 拷贝日志
do_copy_log() {
  new_sysroot_dir=$(get_value new-root)
  msg "正在拷贝安装日志..."
  cp -r /var/log/installer/ $new_sysroot_dir/var/log/
}


do_del_auti_mode() {
  if [[ -f /target/etc/xdg/autostart/oem-qc.desktop ]]; then
        rm -f /target/etc/xdg/autostart/oem-qc.desktop
  fi

  if [[ -f /target/usr/sbin/oem-second ]]; then
        rm -f /target/usr/sbin/oem-second
  fi
  
  if [[ -f /target/etc/xdg/autostart/oem-unlock.desktop ]]; then
        rm -f /target/etc/xdg/autostart/oem-unlock.desktop
  fi
  
  if [[ -f /target/usr/sbin/oem-unlock ]]; then
        rm -f /target/usr/sbin/oem-unlock
  fi
  if [[ -d /target/usr/share/oem-test ]]; then
       mv /target/usr/share/oem-test/ /usr/share/
  fi
  
  if [[ -e /usr/share/kylin-os-installer/99-ukui-installer.conf ]]; then
        mv /usr/share/kylin-os-installer/99-ukui-installer.conf /usr/share/lightdm/lightdm.conf.d
  fi

  if grep -q 'test-mode' /proc/cmdline; then
    oem_mode="oem-automatic"
  else
    oem_mode="oem"
  fi
  cp -a /target/usr/share/applications/kylin-os-installer.desktop /target/etc/xdg/autostart || echo "kylin-os-installer.desktop is unexit" >>/target/var/log/installer/kylin-os-installer.log
  sed -i "/Exec/d" /target/etc/xdg/autostart/kylin-os-installer.desktop
  echo "Exec=/usr/bin/kylin-os-installer-${oem_mode}" >>/target/etc/xdg/autostart/kylin-os-installer.desktop
}

do_auti_mode() {
  
  if [[ -d /usr/share/oem-test ]]; then
       mv /usr/share/oem-test /target/usr/share/
  fi
  if [[ -f /target/usr/share/kylin-os-installer/data/oem-qc.desktop ]]; then
       cp -a /target/usr/share/kylin-os-installer/data/oem-qc.desktop /target/etc/xdg/autostart
       cp -a /target/usr/share/kylin-os-installer/data/oem-qc /target/usr/sbin/oem-qc

       if grep -q 'auti-only' /proc/cmdline; then
              cp -a /target/usr/share/kylin-os-installer/scripts/oem.sh /target/usr/sbin/oem-second
              if [[ -f /cdrom/ky-installer.cfg ]]; then
                      cp /cdrom/ky-installer.cfg /target/usr/share/kylin-os-installer/ky-installer.cfg
              fi
       else
              cp -a /target/usr/share/kylin-os-installer/scripts/oem-second /target/usr/sbin/
       fi
   fi
   
   if [[ -f /target/usr/share/kylin-os-installer/data/oem-unlock.desktop ]]; then
              cp -a /target/usr/share/kylin-os-installer/data/oem-unlock.desktop /target/etc/xdg/autostart
              cp -a /target/usr/share/kylin-os-installer/data/oem-unlock /target/usr/sbin/oem-unlock
   fi

   if [[ -f /target/etc/xdg/autostart/kylin-os-installer.desktop ]]; then
        rm -f /target/etc/xdg/autostart/kylin-os-installer.desktop
   fi

}

# 出厂备份
do_factory_backup() {
  #删除出厂备份中的审核模式
  if grep -q 'auti-mode' /proc/cmdline; then
  	do_del_auti_mode  
  fi

  umount /target/backup
  msg "正在进行系统备份..."
  ## 工厂备份
  /usr/bin/backup-auto --factorybackup /target /backup || true
  msg "系统备份完成"

  #还原出厂备份中的审核模式
  if grep -q 'auti-mode' /proc/cmdline; then
        do_auti_mode
  fi

}

do_install_success() {
  if [[ "${is_990_9a0}" == "true" ]]; then
    mkdir -p /target/boot/efi
    touch /target/boot/efi/INSTALL_SUCCESS
  fi
}

handle_factory_backup() {
  factory_backup=$(get_value factory-backup)
  if [[ -f /target/etc/.bootinfo ]]; then
    if grep -q 'factory-backup' /proc/cmdline; then
      do_factory_backup
    elif [[ $factory_backup -eq 1 ]]; then
      do_factory_backup
    fi
  fi
}

do_finished() {
  echo 'finished'
  touch /tmp/z-finished-install
}

do_os_prober() {
  dmsetup ls |while read line
  do
        if [ "$line" = "No devices found" ];then
                break
        fi
        PART=`echo "$line"|awk '{print $1}'`
        dmsetup remove $PART || true
  done
}

do_select_disk() {
  if grep -q automatic /proc/cmdline; then
        devpath=$(get_value devpath)
        if [[ -z $devpath ]]; then
                 auto_disk >>${LOG_FILE}
        else
                 get_disk  >>${LOG_FILE}
        fi
  elif grep -qE 'ple-mode|test-mode' /proc/cmdline; then
        devpath=$(get_value devpath)
        if [[ -z $devpath ]]; then
                 auto_disk >>${LOG_FILE}
        else
                 get_disk  >>${LOG_FILE}
        fi
  fi

  data_device=$(get_value data-device)
  if [[ ${data_device} == "auto" ]]; then
	automatic=$(get_value automatic-installation)
	if [[ "$automatic" == "0" ]]; then
  		echo "GUI custom installation"
	else 
		get_data_disk >>${LOG_FILE}
	fi
  fi
}

do_apps_third() {
  new_sysroot_dir=$(get_value new-root)
  if [[ -d /cdrom/apps-third ]]; then
  	if [[ -d $new_sysroot_dir/etc/apt/sources.list.d ]]; then
		echo "$new_sysroot_dir/etc/apt/sources.list.d is exit"
	else
		mkdir -p $new_sysroot_dir/etc/apt/sources.list.d
	fi
	echo "deb [trusted=yes] file:///opt/apps-third/ ./" >$new_sysroot_dir/etc/apt/sources.list.d/kylin-apps-third.list
	chroot $new_sysroot_dir apt-get update --allow-insecure-repositories -y || true
  fi
}

rm_deploy_systemroot_usr_config() {
  cat "/usr/share/kylin-os-installer/scripts/ostree_system_usr_etc_config" | while read filename
  do
    echo "$filename"
    realPathFilename="$1$filename"
    [ -f $realPathFilename ] && rm $realPathFilename
  done

}

get_ostree_release_file_info() {
	while read os_release_file_line
	do
		if [ "$os_release_file_line" = "[info]" ]; then
			sign_position=0
			continue
		fi

		if [ $sign_position = 0 ] && [ "$os_release_file_line" != "[info]" ]; then
			info_version_string=$os_release_file_line
			sign_position=1
			continue
		fi

		if [ "$os_release_file_line" != "[metadata]" ]; then
			mate_data_add_string="$mate_data_add_string --add-metadata-string=$os_release_file_line"
		fi

	done < "/etc/ostree-release"

	info_version_string=${info_version_string#*version=}
	os_version_name=$(echo "$info_version_string" | awk -F ":" '{print $1}')
	echo "$os_version_name" >> ${LOG_FILE} 2>&1
	echo "$info_version_string" >> ${LOG_FILE} 2>&1
	echo "$mate_data_add_string" >> ${LOG_FILE} 2>&1
}


# 解决os-prober问题
do_os_prober >>${LOG_FILE} 2>&1

#安装自动选择磁盘安装方案
do_select_disk >>${LOG_FILE} 2>&1

# 运行 prepare 阶段脚本
do_prepare >>${LOG_FILE} 2>&1

# 执行 target inchroot 脚本
do_run_target

# 运行 after 阶段脚本
do_after >>${LOG_FILE} 2>&1

# 执行 postactions 脚本
do_cdrom_post_actions

#配置apps-third源
do_apps_third >>${LOG_FILE} 2>&1

# 拷贝安装日志
do_copy_log

do_install_success

# 处理出厂备份
handle_factory_backup >>${LOG_FILE} 2>&1

# 卸载文件系统
#umount_all

do_finished
