#!/bin/bash

set -e

do_user_file() {
	old_file=$1
	new_file=$2
	
	user_name=
	user_names=
	user_names=`cat "/tmp/etc/passwd" | grep home | grep "/bin/bash"`
	for i in ${user_names}; do
		user_name=${i%%:*}
        	echo "${user_name}"
		cat $1 | grep "^${user_name}:" >> $2 || true
	done

}

set_swap() {
  while (true); do
    if ! echo ${array} | grep -q linux-swap; then
        break
    fi
    swaptmp=${array#*linux-swap:}
    swapdev=$(echo ${swaptmp%%|*})
    #mkswap ${swapdev}
    if echo "${swapdev}" | grep -q lvm; then
        swapdev=/dev/kylin-vg/swap
    fi
    swapon ${swapdev}

    array=$(echo ${swaptmp} | cut -d'\' -f2-)
  done
}


automatic=$(get_value automatic-installation)
if [[ $automatic -eq 0 ]]; then

  partlists=$(get_value partitions | sed 's/\"//g')
  array_space=${partlists//;/ }
  array=${partlists//;/|}

  list=
  for i in ${array_space[@]}; do
    list="$list $(echo $i | cut -d: -f1)"
  done
  sort_list=$(echo $list | tr ' ' '\n' | sort)

  for mountpoint in $sort_list; do
    dev0=$(echo ${array#*$mountpoint:})
    dev=$(echo ${dev0%%|*})

    if echo "${dev}" | grep -q lvm; then
        case $mountpoint in
        'kylin-data')
                dev=/dev/kylin-vg/data
                ;;
        'linux-swap')
                dev=/dev/kylin-vg/swap
                ;;
        '/')
                dev=/dev/kylin-vg/root
                ;;
        '/backup')
                dev=/dev/kylin-vg/backup
                ;;
        *)
                dev=/dev/kylin-vg/$mountpoint
                ;;
        esac
    fi

    if [[ $mountpoint == "linux-swap" ]]; then
      continue
    fi

    if [[ $mountpoint == "kylin-data" ]]; then
      mkdir -p /target/data
      mount $dev /target/data
      chmod 1777 /target/data
      do_bind_data
      continue
    fi
    
    if [[ $mountpoint == "empty" ]]; then
      continue
    fi

    mkdir -p /target$mountpoint
    mount $dev /target$mountpoint
    
    if [[ $mountpoint == "/backup" ]]; then
      set_backup $dev
    fi

    if [[ $mountpoint == "/data" ]]; then
      chmod 1777 /target$mountpoint >/dev/null
    fi
  done

  nomount_list=$(echo ${array_space} | tr ' ' '\n' | sort | grep empty) || true
  if [[ -n ${nomount_list} ]]; then
	empty_num=1
  	for mountpoint in ${nomount_list}; do
      		dev=$(echo ${mountpoint#*:})
		if echo "${dev}" | grep -q lvm; then
                        dev=/dev/kylin-vg/kylin${empty_num}
                        empty_num=$(( empty_num + 1 ))
                fi
     		mkdir -p /target/nomountpoint
      		mount $dev /target/nomountpoint
      		chmod -R 1777 /target/nomountpoint
      		umount -l /target/nomountpoint
      		rmdir /target/nomountpoint
  	done
  fi

  set_swap
fi

case ${LANGUAGES} in
        'zh_CN')
                echo "磁盘挂载完成" >>${LOG_PROGRESS_FILE}
                ;;
        'en_US')
                echo "Disk mounting completed" >>${LOG_PROGRESS_FILE}
                ;;
        'bo_CN')
                echo "འཁོར་གཞོང་挂载ལེགས་གྲུབ།" >>${LOG_PROGRESS_FILE}
                ;;
        'zh_HK')
                echo "磁片掛載完成" >>${LOG_PROGRESS_FILE}
                ;;
        'mn_MN')
                echo "ᠰᠣᠷᠢᠨᠵᠢᠨ ᠳ᠋ᠢᠰᠺ ᠢ ᠴᠢᠷᠴᠦ ᠳᠠᠭᠤᠰᠪᠠ" >>${LOG_PROGRESS_FILE}
                ;;
              *)
                echo "磁盘挂载完成" >>${LOG_PROGRESS_FILE}
                ;;
esac

deal_squashfs() {
  if [[ "${is_minimal}" == "true" ]]; then
    minimal_squashfs=$(find /cdrom/casper -name '*img' | head -1)
    # 挂载最小系统镜像
    if [[ $minimal_squashfs =~ 'img' ]]; then
      mount -r $minimal_squashfs /rofs
    fi
  elif [[ "${is_ghost}" == "true" ]]; then
    if [[ -f /target/etc/.bootinfo ]]; then
    	cp -a /target/etc/.bootinfo /etc
    fi
    ghost_img=$(get_value ghost-path)
    
    if [[ -f ${ghost_img} ]]; then
	echo "img is file,don't to transformed"
    else
	dev_img=${ghost_img}
	dev_img=${dev_img##*(} || true
	dev_img=${dev_img%%)*} || true

	process_img=${ghost_img}
	if [[ -b ${dev_img} ]]; then
		mkdir -p /ghost
		umount /var/log/installer/ghost || true
		umount "/dev/${os_disk}*"|| true
		mount ${dev_img} /ghost
		process_img=${process_img%(*}

		ghost_img=/ghost/${process_img}
    		if [[ -f ${ghost_img} ]]; then
			echo "ghost镜像在磁盘跟目录"
		else
			ghost_img=/ghost/ghost/${process_img}
		fi
	else
		echo "您现在用的是ghost安装，移动设备暂无可用ghost镜像，请检查ghost镜像位置"
	fi
    fi

    # 挂载 ghost 镜像
    if [[ ${ghost_img} =~ 'img' ]]; then
       mkdir -p /img
       mount -r "${ghost_img}" /img || true
    fi
  fi
}

# 判断使用最小系统镜像或 ghost
deal_squashfs


case ${LANGUAGES} in
        'zh_CN')
                echo "正在拷贝基础文件系统..." >>${LOG_PROGRESS_FILE}
                ;;
        'en_US')
                echo "Copying basic file system..." >>${LOG_PROGRESS_FILE}
                ;;
        'bo_CN')
                echo "བཞིན་གྱི་པར་ཤོག་རྨང་གཞི་ཡིག་ཆ་མ་ལག།..." >>${LOG_PROGRESS_FILE}
                ;;
        'zh_HK')
                echo "正在拷貝基礎檔案系統..." >>${LOG_PROGRESS_FILE}
                ;;
        'mn_MN')
                echo "ᠶᠠᠭ ᠰᠠᠭᠤᠷᠢ ᠹᠠᠶᠢᠯ ᠤᠨ ᠰᠢᠰᠲ᠋ᠡᠮ ᠢ ᠺᠣᠫᠢᠳᠠᠵᠤ ᠪᠠᠶᠢᠨᠠ..." >>${LOG_PROGRESS_FILE}
                ;;
              *)
                echo "正在拷贝基础文件系统..." >>${LOG_PROGRESS_FILE}
                ;;
esac


msg "正在拷贝基础文件系统..."
if [[ "${is_ghost}" == "true" ]]; then
	rsync -aHAX /img/ /target  || do_error copy
else
	rsync -aHAX /rofs/ /target || do_error copy
fi
msg "文件系统拷贝完成"
sync

case ${LANGUAGES} in
        'zh_CN')
                echo "文件系统拷贝完成" >>${LOG_PROGRESS_FILE}
                ;;
        'en_US')
                echo "File system copy completed" >>${LOG_PROGRESS_FILE}
                ;;
        'bo_CN')
                echo "ཡིག་ཆ་མ་ལག་གྱི་པར་ཤོག་ལེགས་གྲུབ།" >>${LOG_PROGRESS_FILE}
                ;;
        'zh_HK')
                echo "檔案系統拷貝完成" >>${LOG_PROGRESS_FILE}
                ;;
        'mn_MN')
                echo "ᠹᠠᠢᠯ ᠤ᠋ᠨ ᠱᠢᠰᠲ᠋ᠧᠮ ᠦ᠋ᠨ ᠺᠣᠪᠢ ᠪᠡᠶᠡᠯᠡᠭᠳᠡᠪᠡ" >>${LOG_PROGRESS_FILE}
                ;;
              *)
                echo "文件系统拷贝完成" >>${LOG_PROGRESS_FILE}
                ;;
esac


if [[ "${is_ghost}" == "true" ]]; then
    umount "${ghost_img}" || echo "umount $ghost_img failed"
    umount /ghost || echo "umount /ghost failed"
    umount /img || echo "umount /img failed"
    if [[ -f /etc/.bootinfo ]]; then
    	cp -a /etc/.bootinfo /target/etc
    fi
fi

# 加密
if [[ "${isluks_lvm}" == "true" ]] || [[ "${tpm}" == "true" ]]; then
  rsync /etc/crypttab /target/etc
  rm -f /target/etc/grub.d/05* || true
  rm -f /target/etc/grub.d/06* || true
fi

# 保留data
data_unformat=$(get_value data-unformat)
if [[ "${data_unformat}" == "true" ]]; then

	if [[ -f /tmp/etc/passwd ]]; then
		do_user_file /tmp/etc/passwd /target/etc/passwd
		
		if [[ -f /tmp/etc/passwd- ]]; then
    			do_user_file /tmp/etc/passwd- /target/etc/passwd-
		fi

		if [[ -f /tmp/etc/shadow ]]; then
			do_user_file /tmp/etc/shadow /target/etc/shadow
		fi
		if [[ -f /tmp/etc/shadow- ]]; then
			do_user_file /tmp/etc/shadow- /target/etc/shadow-
		fi

		if [[ -f /tmp/etc/group ]]; then
			do_user_file /tmp/etc/group /target/etc/group
			if [[ -f /usr/share/kylin-os-installer/user-groups.txt ]]; then
                        	cp -a  /usr/share/kylin-os-installer/user-groups.txt /target/usr/share/kylin-os-installer || true
                	fi
		fi
		if [[ -f /tmp/etc/group- ]]; then
			do_user_file /tmp/etc/group- /target/etc/group-
		fi

		if [[ -f /tmp/etc/gshadow ]]; then
			do_user_file /tmp/etc/gshadow /target/etc/gshadow
		fi
		if [[ -f /tmp/etc/gshadow- ]]; then
			do_user_file /tmp/etc/gshadow- /target/etc/gshadow-
		fi
		if [[ -f /tmp/etc/uid_list ]]; then
			do_user_file /tmp/etc/uid_list /target/etc/uid_list
		fi
	fi
        
	if [[ -f /tmp/etc/subgid ]]; then
                cp -a /tmp/etc/subgid* /target/etc
        fi
	if [[ -f /tmp/etc/subuid ]]; then
                cp -a /tmp/etc/subuid* /target/etc
        fi


	if [[ -f /tmp/etc/hostname ]]; then
     		cp -a /tmp/etc/hostname /target/etc
	fi
	if [[ -f /tmp/etc/hosts ]]; then
     		cp -a /tmp/etc/hosts /target/etc
	fi
        if [[ -f /tmp/etc/lightdm/lightdm.conf ]]; then
                cp -a /tmp/etc/lightdm/lightdm.conf /target/etc/lightdm
        fi
	
	# 保留激活文件
	if [[ -f /tmp/etc/.kyhwid ]]; then
                cp -a /tmp/etc/.kyhwid /target/etc/
        fi
        if [[ -f /tmp/etc/.kyactivation ]]; then
                cp -a /tmp/etc/.kyactivation /target/etc/
        fi
        if [[ -f /tmp/etc/.product ]]; then
                cp -a /tmp/etc/.product /target/etc/
        fi

	if [[ "${isluks_lvm}" == "true" ]] || [[ "${tpm}" == "true" ]]; then
                if [[ -f /tmp/etc/crypttab ]]; then
                        cp -a /tmp/etc/crypttab /target/etc
                fi
                if [[ -f /tpm/etc/hk_tpm.log ]]; then
                        cp -a /tpm/etc/hk_tpm.log /target/var/log
                fi
        fi
fi

if [[ -f /usr/share/kylin-os-installer/ky-installer.cfg ]]; then
        cp -a /usr/share/kylin-os-installer/ky-installer.cfg /target/usr/share/kylin-os-installer
fi
if [[ -f /var/log/hk_tpm.log ]]; then
        cp -a /var/log/hk_tpm.log /target/var/log || echo "copy /var/log/hk_tpm.log failed"
fi

#拷贝可选安装包
if [[ -d /cdrom/apps-third ]]; then
#        cp -a /cdrom/apps-third /target/opt
	rsync -aHA /cdrom/apps-third /target/opt

	if [[ -f /opt/apps-third/install.list ]]; then
		cp -a /opt/apps-third/install.list /target/opt/apps-third/install.list
	fi
	
        if cat /proc/cmdline | grep -qi automatic ;then
                if [ "x$is_oem_mode" = "xfalse" ];then
                        if [ -f /target/opt/apps-third/install.list ];then
                                rm -f /target/opt/apps-third/install.list
                        fi
                        /usr/share/kylin-os-installer/scripts/preinstall-scan.py
       		else
	       		if cat /proc/cmdline | grep -qi auti-only ;then
                        	/usr/share/kylin-os-installer/scripts/preinstall-scan.py
			fi
		fi
	else
        	if cat /proc/cmdline | grep -qi test-mode ;then
                	if [ "x$is_oem_mode" = "xfalse" ];then
                        	if [ -f /target/opt/apps-third/install.list ];then
                                	rm -f /target/opt/apps-third/install.list
                        	fi
                        	/usr/share/kylin-os-installer/scripts/preinstall-scan.py
       			else
                        	/usr/share/kylin-os-installer/scripts/preinstall-scan.py
			fi
		fi
        fi
fi

#显卡测试拷贝结果
if [ -f "/tmp/kwin-backend.config" ]; then
    chmod 644 /tmp/kwin-backend.config
    cp /tmp/kwin-backend.config /target/etc/xdg/
fi

case ${LANGUAGES} in
        'zh_CN')
                echo "正在配置系统..." >>${LOG_PROGRESS_FILE}
                ;;
        'en_US')
                echo "Configuring the system..." >>${LOG_PROGRESS_FILE}
                ;;
        'bo_CN')
                echo "བཞིན་བཀོད་སྒྲིག་བྱེད་པའི་མ་ལག།..." >>${LOG_PROGRESS_FILE}
                ;;
        'zh_HK')
                echo "正在配寘系統..." >>${LOG_PROGRESS_FILE}
                ;;
        'mn_MN')
                echo "ᠶᠠᠭ ᠰᠢᠰᠲ᠋ᠡᠮ ᠢ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠵᠤ ᠪᠠᠶᠢᠨᠠ..." >>${LOG_PROGRESS_FILE}
                ;;
              *)
                echo "正在配置系统..." >>${LOG_PROGRESS_FILE}
                ;;
esac

