#!/bin/bash

set -e
set -o pipefail

# 拷贝配置文件
do_copy_config() {
  # 使用绝对路径，方便在 /target 中加载
  cp utils /tmp

  # sp1 使用 automatic
  if grep -q automatic /proc/cmdline; then
    [[ -f /cdrom/ky-installer.cfg ]] && cp /cdrom/ky-installer.cfg /tmp
  # 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
}

do_copy_config

. /tmp/utils


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

  run_scripts_dir prepare

  if [[ -d /cdrom/hooks/prepare ]]; then
    run_scripts_dir /cdrom/hooks/prepare
  fi
}

# 运行 in_chroot 脚本
do_run_target() {
  mkdir -p /target/${IN_TARGET}
  cp utils /tmp/ky-installer.cfg /target/tmp
  cp -r k.sh in_chroot /target/${IN_TARGET}

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

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

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

# 执行 post 脚本
do_cdrom_post_actions() {
  if [[ -f /cdrom/.kylin-post-actions ]] && [[ "${is_ghost}" != "true" ]]; then
    cp /cdrom/.kylin-post-actions /target/${IN_TARGET}
    chroot /target 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() {
  msg "正在拷贝安装日志..."
  cp -r /var/log/installer/ /target/var/log/
}

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

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
}

# 运行 prepare 阶段脚本
mkdir -p /var/log/installer

#自动安装自动选择磁盘安装方案
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
fi


do_prepare >>${LOG_FILE} 2>&1

# 执行 target inchroot 脚本
do_run_target

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

# 执行 postactions 脚本
do_cdrom_post_actions

# 拷贝安装日志
do_copy_log

do_install_success

# 处理出厂备份
handle_factory_backup

# 卸载文件系统
umount_all

do_finished
