#!/usr/bin/env bash

version="Refracta UEFI/BIOS Installer (Yad) 9.6.1 (20220212"

TEXTDOMAIN=refractainstaller-gui
TEXTDOMAINDIR=/usr/share/locale/


 # Copyright 2011-2021 fsmithred@gmail.com
 # Portions may be copyright Dean Linkous and/or David Hare and/or others.
 # UEFI code adapted from contributions by Peter Pranter.
 # Based on refractainstaller-8.0.3 by Dean Linkous
 # License: GPL-3
 # This is free software with NO WARRANTY. Use at your own risk!

# DESCRIPTION
# This script is used for installing a live system to a hard drive. User
# input is via popup windows created by yad. It should be run from
# a terminal; if it's started from a menu item or a panel launcher, it
# should be run in a persistent terminal, so that progress messages can
# be seen and for user input in a few places.
#
# User selects installation options - change username, select up to three
# partitions (/, /boot, /home), select filesystem type for each partition, 
# choose whether to encrypt partitions or not, choose whether to write 
# random data or zeros to partitions.
# User has option to exit and use custom excludes file.
# User can run partitioner inside the installer.
# Summary window asks to proceed with installation.
# Stuff happens with some interaction (passwords, username, edit /etc/sudoers)
#
#  Stuff:
# Cleanup (in case of previous aborted run)
# Create encrypted volumes
# Write random data or zeros
# Mount partition(s) and create filesystem(s)
# Copy system with rsync
# Create swapfile or use existing swap partition
# Copy update-initramfs
# Set up fstab
# Set up crypttab
# Install bootloader
# Cleanup
# Change username and passwords, edit /etc/sudoers



# If you want to change any defaults, change them in the configfile.
# Default is /etc/refractainstaller.conf
# If you want to use a different config file for testing, change this
# variable. Normally, users should not edit anything in this script.

configfile="/etc/refractainstaller.conf"

if [[ -f $configfile ]]; then
    source $configfile
else
	yad --title=$"Warning" --window-icon=error \
	--button=$"Exit":0 --center --borders=10 \
	--text=$"  Config file $configfile is missing.  
  "
	echo $" Config file $configfile is missing."
	exit 1
fi


# greeter window title
if [ -z "$window_title" ]; then
window_title="$version"
fi

show_help () {
	printf "$help_text"
	exit 0
}

help_text=$"
	Usage:  $0  [option]
	
	Запустите refractainstaller-yad из терминала без параметров
	или выберите Refracta Installer из системного меню для установки
	работающий live-CD или live-usb-hdd на жесткий диск. 
	
	
	допустимые параметры:
		-h, --help		показать этот текст помощи
		-v, --version	отображать информацию о версии
		-d. --debug		режим отладки
		
"

while [[ $1 == -* ]]; do
	case "$1" in
	
		-h|--help)
			show_help ;;
		
		-v|--version)
			printf "\n$version\n\n" 
			exit 0 ;;
			
		-d|--debug)
			DEBUG="yes"
			break ;;
		
		*) 
			printf $"\t invalid option: $1 \n\n"
			printf $"\t Try:  $0 -h for full help. \n\n"
			exit 1 ;;
    esac
done

# Always run graphical installer in debug mode. 
# (setting it in wrapper script no longer works.)
	set -x

# Check that xserver is running and user is root.
[[ $DISPLAY ]] || { echo $"Нет работает xserver. Выход..." ; exit 1 ; }
if [[ $(id -u) -ne 0 ]] ; then
	yad --title=$"Error" --window-icon=error --center --borders=10 --text=$" 
	Вы должны быть пользователем root!
"
	exit 1
fi

# wrapper script starts installer in xterm. 
clear
echo $"НЕ закрывайте это окно терминала, пока установка не будет завершена."

# Record errors in a logfile.
exec 2>"$error_log"
echo "Version:	$version" >> "$error_log"
#******************************************************************

# Make sure yad is installed, and check the version. *** What version is really needed??? ***
if [[ -f /usr/bin/yad ]] ; then
	yadversion=$(yad --version | cut -d. -f2)
	if [[ $yadversion < 27 ]]; then
		yad --title=$"Ошибка" --window-icon=error --center --borders=10 --text=$"
	Версия Yad слишком старая. Вам нужно 0,27 или позже.
"
		exit 1
	fi
else
	echo $"Yad не установлен. Чтобы использовать версию cli вместо этого, запустите 'refractainstaller' из корневого терминала.
Выходящий..."
	exit 1
fi


if [[ ! -d /lib/live/mount/medium ]] && [[ ! -d /lib/live/mount/findiso ]] && [[ ! -d /lib/live/mount/fromiso ]] && [[ ! -d /lib/live/mount/persistence ]] && [[ ! -d /run/live/medium ]] ; then
	live_session_warning=$" ###	ВНИМАНИЕ: Не работает с live-CD или live-USB	### 
 ###	или неподдерживаемая конфигурация. Будь уверен, что ты знаешь	### 
 ###	что ты делаешь. Это может не сработать.			### "
fi


# Greeting window
yad --title="$window_title" --width=540 --height=500 --center --borders=10 \
	--button=$"Continue":0 --button=$"Exit":1 \
	--text=$"$live_session_warning

 Эта утилита установит работающий live-CD или live-USB на ваш жесткий диск.

 Это бесплатное программное обеспечение, которое поставляется без каких-либо гарантий тип,
 включая, но не ограничиваясь, выраженный, подразумеваемый, товарный вид или пригодность цели. 

 Copyright 2011-2020 fsmithred@gmail.com, 
 based on refractainstaller-8.0.3 by Dean Linkous. \n Version: $version \n\n\
 ${custom_text}\n

 "
if [[ $? -ne 0 ]] ; then
	exit 0
fi

# Fix root's path (for Buster/Beowulf and later)
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# function to exit the script if there are errors
check_exit () {
exit_code="$?"
if [[ $exit_code -ne 0 ]] ; then
   yad --question --title=$"Error" --window-icon=error --center --borders=10 --button=$"Continue":0 --button=$"Exit now":1 \
   --text=$"Error detected: $exit_code  $error_message
\nSee $error_log for details. \n\nThis may not be fatal.. Press \"Continue\" to proceed anyway"
# Add button "See error log" ? If so, remove "&" and add continue/exit buttons
#less "$error_log" | yad --text-info --title="Error Log" --width=600 --height=500 --borders=10 \
#	--button=$"Close":0 &
   if [[ $? -ne 0 ]] ; then
   cleanup
   exit 1
   fi
fi
}


copy_excludes () {
        cat > "$rsync_excludes" <<EOF
# It is safe to delete this file after installation.

- /dev/*
- /cdrom/*
- /media/*
- /target
- /swapfile
- /mnt/*
- /sys/*
- /proc/*
- /tmp/*
- /live
- /boot/grub/grub.cfg
- /boot/grub/menu.lst
- /boot/grub/device.map
- /etc/udev/rules.d/70-persistent-cd.rules
- /etc/udev/rules.d/70-persistent-net.rules
- /etc/fstab
- /etc/fstab.d
- /etc/mtab
- /home/snapshot/
- /home/*/.gvfs
- /var/lib/dbus/machine-id
- /etc/popularity-contest.conf

# Added for newer version of live-config/live-boot
# in sid (to become Jessie)
- /lib/live/overlay
- /lib/live/image
- /lib/live/rootfs
- /lib/live/mount
- /run/*

# Added for symlink /lib
- /usr/lib/live/overlay
- /usr/lib/live/image
- /usr/lib/live/rootfs
- /usr/lib/live/mount

EOF

    chmod 666 "$rsync_excludes"
}



# Check that rsync excludes file exists, or create one.
if ! [[ -f  $rsync_excludes ]] ; then
    yad --title=$"Предупреждение" --window-icon=error --center --borders=10 \
    --button=$"Продолжить":0 --button=$"Выйти":1 \
    --text=$"  Нет никакого файла rsync, или его имя не соответствует тому, что ожидает этот скрипт.  
  Вы должны продолжить и позволить сценарию создать его, или если у вас есть специальный файл исключений,
  и вы знаете, что делаете, вы можете выйти из сценария и отредактировать переменную
  rsync_exclude в $configfile чтобы оно соответствовало названию и 
  пути вашего пользовательского файла.
    
  Если у вас есть какие-либо другие диски или разделы, которые вам не нужны чтобы скопировать,
  размонтировать их или отредактировать файл исключений, чтобы перечислить их."
    if [[ $? = 0 ]] ; then
		rsync_excludes="$(pwd)/installer_exclude.list"
        copy_excludes
        echo $"@@@ copied excludes to $(pwd)" >> "$error_log"
    else
        exit 0
    fi
fi


#******************************************************************

###  UEFI TESTS

# Test for efi boot
# Test for esp partition
# Test for grub version

grubversion=$(dpkg -l | egrep "ii  grub|hi  grub" | grep -v bin | grep -v doc | awk '$2 ~ "grub-[eglp]" { print $2}')
gpt_list=$(env LC_ALL=C fdisk -l | awk '/Disklabel type/ { print $3 }' | grep gpt)
bios_grub_dev=$(env LC_ALL=C fdisk -l | awk '/BIOS boot/ { print $1 }')


show_installer_help () {

	zless "$installer_help" | yad --text-info --title="$window_title" --width=600 --height=500 --borders=10 \
	--button=$"Close":0 &
	sleep 2

}

# Check for UEFI boot and EFI partition

esp_count=$(env LC_ALL=C fdisk -l | awk '/EFI System/ { print $0 }' | wc -l)

if [[ -d /sys/firmware/efi ]]; then
	uefi_boot="yes"
	if [ -z "$gpt_list" ] ; then
		gpt_message=$"Нет диска с таблицей разделов gpt.
Вы должны выйти из этого скрипта и запустить gdisk, чтобы создать его для загрузки UEFI."
	fi
	if [ "$esp_count" -eq 1 ] ; then
		esp_dev=$(env LC_ALL=C fdisk -l | awk '/EFI System/ { print $1 }')
		esp_dev_message=$"EFI раздел найден на $esp_dev\nЕсли это не на первом жестком диске, возможно, что-то не так, и вам следует изучить ситуацию."
		if ! blkid -c /dev/null -s TYPE "$esp_dev" | grep -q "vfat" ; then
			must_choose_esp="yes"
			esp_dev_message=$"ВНИМАНИЕ: раздел EFI найден в $esp_dev не содержит файловой системы FAT32.\nВы можете отформатировать ее с помощью разделителя или установить систему без загрузчика."
		fi
	else
		must_choose_esp="yes"
		if [ "$esp_count" -eq 0 ] ; then
			esp_dev_message=$"Там нет раздела EFI. Вам нужно будет создать один или инсталлировать систему без загрузчика."
		elif [ "$esp_count" -gt 1 ] ; then
			esp_dev_message=$"Обнаружено более одного раздела EFI. Вам нужно будет выбрать один. Обычно это на первом жестком диске."
		fi
	fi

	if ! [[ "$grubversion" =~ grub-efi ]] ; then   # grub-efi-${grub_arch}*.deb to include grub-efi-ia32
		grub_package="grub-efi*.deb"  # make sep vars for grub-x and grub-x-bin. Maybe sep. messages. Or sep. dirs?
		grub_debs=$(ls "$grub_package_dir"/${grub_package})    # don't quote $grub_package here.
		if [[ -n "$grub_debs" ]] ; then
			grub_package_message=$"grub package(s) found in $grub_package_dir"
		fi
		grub_efi_warning=$"			### ПРЕДУПРЕЖДЕНИЕ ### 
	grub-efi не устанавливается. 

	Если у вас есть пакеты deb, вам будет предоставлена возможность установить
	их в новую систему.

	${grub_package_message}
${grub_debs}
"
	fi

	yad --title=$"$window_title" --width=480 --button=$"Help":0 \
	--button=$"Continue":1 --button=$"Exit":2 --center --borders=10 \
	--text=$"
${gpt_message}
${gpt_message}
${esp_dev_message}

НЕ ФОРМАТИРУЙТЕ ПРЕДШЕСТВУЮЩИЙ EFI РАЗДЕЛ!!!
	"
	answer="$?"
	case "$answer" in 
		0) show_installer_help ;;
		1) ;;
		2) exit 0 ;;
	esac
else
	# not uefi, do bios install.
	esp_list=$(env LC_ALL=C fdisk -l | awk '/EFI System/ { print $0 }')
	if [ "$esp_count" -eq 1 ] ; then
		esp_dev=$(env LC_ALL=C fdisk -l | awk '/EFI System/ { print $1 }')
		esp_dev_message=$"EFI раздел найден на $esp_dev.
Не форматируйте разделы EFI, если вы планируете использовать их для загрузки UEFI."
	elif [ "$esp_count" -gt 1 ] ; then
		esp_dev_message=$"Обнаружено более одного раздела EFI. Они появятся в списках выбора разделов.
Не выбирайте разделы EFI, если планируете использовать их для загрузки с UEFI.
${esp_list}"
	fi

	if [ -n "$gpt_list" ] && [ -z "$bios_grub_dev" ] ; then
		gpt_message=$"ВНИМАНИЕ: Для загрузки диска gpt в устаревшем BIOS вы должны создать небольшой (> 1M) неформатированный раздел с флагом bios_grub в parted / gparted или EF02 в gdisk. Или загрузиться с диска с таблицей разделов.
Больше информации: http://www.rodsbooks.com/gdisk/bios.html"
	fi
###### grub-pc and grub-pc-bin get installed out of order
###### Need to make $grub_package and $grub_bin_package
###### and install them in correct order.
	if  [[ "$grubversion" =~ grub-efi ]] || [[ -z "$grubversion" ]] ; then
		grub_package="grub-pc*.deb"
		grub_debs=$(ls "$grub_package_dir"/${grub_package})  # don't quote $grub_package here.
		if [[ -n "$grub_debs" ]] ; then    
			grub_package_message=$"пакет(ы) grub найден в $grub_package_dir"
		fi
		grub_efi_warning=$"				### ПРЕДУПРЕЖДЕНИЕ ### 
	grub-pc не установлен, но вы загрузились в режиме BIOS.

Если у вас есть пакеты deb для grub-pc, вам будет предоставлена возможность установить их в новую систему.

	${grub_package_message}
${grub_debs}
"
	elif [[ "$grubversion" =~ "grub-pc" ]] ; then
		grub_efi_warning=$"Метод загрузки: биос
Версия GRUB: grub-pc (для загрузки BIOS)
Если это не то, что вы хотите, выйдите и изучите ситуацию."
	fi
	yad --title=$"$window_title" --width=480 --button=$"Help":0 \
	--button=$"Continue":1 --button=$"Abort":2 --center --borders=10 \
	--text=$"
${grub_efi_warning}	
	
${esp_dev_message}

${gpt_message}

	"
	answer="$?"
	case "$answer" in 
		0) show_installer_help ;;
		1) ;;
		2) exit 0 ;;
	esac
fi


#******************************************************************


# These set the default setting in the options window,
# based on setting in config file. Simple Install does
# what config file says.
if [[ $run_preinstall = "yes" ]] ; then
	var15="TRUE"
else
	var15="FALSE"
fi
if [[ $run_postinstall = "yes" ]] ; then
	var16="TRUE"
else
	var16="FALSE"
fi

pre_install_list=$(ls -m /usr/lib/refractainstaller/pre-install)
post_install_list=$(ls -m /usr/lib/refractainstaller/post-install)

# Check for swap partition and set default option accordingly.
if [[ $(blkid -c /dev/null | grep swap) ]] ; then
	var3="TRUE"
else
	var3="FALSE"
fi


# Select installation options

opts=$(yad --list --title=$"Варианты установки" --center --borders=10 \
     --text=$"Проверьте параметры, которые вы хотите для установки.\n
Если вы не понимаете опцию, вам, вероятно, она не нужна.\n" \
     --checklist --column $"Выбирать" --column "":HD --column $"Опции" \
     --width=590 --height=555 --button=$"OK":0 --button=$"Выйти":1\
  FALSE 01 $"Создать новый, отдельный /home раздел" \
  FALSE 02 $"Создайте отдельный раздел /boot" \
  $var3 03 $"Использовать существующий раздел подкачки вместо файла подкачки." \
  FALSE 04 $"Зашифровать корневую файловую систему (с отдельным разделом /boot или без него)" \
  FALSE 05 $"Зашифруйте раздел /home (требуется отдельный /home)" \
  FALSE 06 $"Запись случайных данных в зашифрованные разделы (более безопасный)" \
  FALSE 07 $"Записать нули во все разделы (чтобы стереть предыдущие данные)" \
  FALSE 09 $"Не форматируйте файловые системы. Я справлюсь сам." \
  TRUE 10 $"Используйте UUID в fstab и crypttab. (Полезно, если порядок дисков меняется.)" \
  FALSE 11 $"Используйте метки файловой системы (метки диска) в /etc/fstab." \
  TRUE 12 $"Отключить автоматический вход на рабочий стол." \
  TRUE 13 $"Отключить автоматический вход в консоль. (только sysvinit)" \
  FALSE 14 $"Переместить выбранные каталоги в отдельные разделы." \
  $var15 15 $"Запустите предустановочные скрипты (перечислены ниже)
$pre_install_list" \
  $var16 16 $"Запустите сценарии после установки (перечисленные ниже)
$post_install_list")

if [[ $? = 1 ]] ; then
	exit 0
fi

if $(echo $opts | grep -q 01); then
    sep_home="yes"
fi
#if $(echo $opts | grep -q 08); then
#	sep_home="yes"
#	keep_old_home="yes"
#	old_home_message=$"Existing /home partition will be used; old files will be preserved."
#fi
if $(echo $opts | grep -q 02); then
    sep_boot="yes"
fi
if $(echo $opts | grep -q 03); then
    use_existing_swap="yes"
fi
if $(echo $opts | grep -q 04); then
    encrypt_os="yes"
fi
if $(echo $opts | grep -q 05); then
#	if [[ -z $keep_old_home ]] ; then
		encrypt_home="yes"
#	else
#		old_home_message=$"Existing /home will not be encrypted; old files will be preserved."
#	fi
fi
if $(echo $opts | grep -q 06); then
    write_random="yes"
fi
if $(echo $opts | grep -q 07); then
    write_zero="yes"               
fi
if $(echo $opts | grep -q 09); then
	if [[ $encrypt_os = "yes" ]] || [[ $encrypt_home = "yes" ]]; then
		no_format=""
	else
		no_format="yes"
	fi
else
	no_format=""     # just in case config file is set to yes.
fi
if $(echo $opts | grep -q 10) || [ "$use_uuid" = "yes" ]; then
	use_uuid="yes"
	if [[ $encrypt_os = "yes" ]] || [[ $encrypt_home = "yes" ]]; then
		uuid_message=$"--> UUIDs будет использоваться в CryptTab,
 /dev/mapper/name будет использоваться в Fstab."
	fi
fi
if $(echo $opts |grep -q 11) || [ "$use_labels" = "yes" ]; then
	if [[ $encrypt_os = "yes" ]] || [[ $encrypt_home = "yes" ]]; then
		disklabel_message=$"--> Метки диска в fstab не будут работать с зашифрованными файловыми системами и не будет использоваться. Отредактируйте fstab вручную после установки"
	else
		use_uuid="no"
		use_labels="yes"
	fi
fi
   
if $(echo $opts | grep -q 12); then
	disable_auto_desktop="yes"
fi
if $(echo $opts | grep -q 13); then
	disable_auto_console="yes"
fi
if $(echo $opts | grep -q 14); then
	if ! [[ -h /usr/lib/refractainstaller/post-install/move-dir-mount-gui.sh ]] ; then
		ln -s /usr/lib/refractainstaller/move-dir-mount-gui.sh /usr/lib/refractainstaller/post-install/move-dir-mount-gui.sh
	fi
	separate_partition_message=$"В конце установки вам будет предоставлена возможность переместить выбранные каталоги в отдельные разделы."
else
	if [[ -h /usr/lib/refractainstaller/post-install/move-dir-mount-gui.sh ]] ; then
		rm /usr/lib/refractainstaller/post-install/move-dir-mount-gui.sh
	fi
fi
if $(echo $opts | grep -q 15); then
	run_preinstall="yes"
else
	run_preinstall="no"
fi
if $(echo $opts | grep -q 16); then
	run_postinstall="yes"
else
	run_postinstall="no"
fi


if [[ $encrypt_os = "yes" ]] || [[ $encrypt_home = "yes" ]]; then
    # test for cryptsetup
    if ! [[ -f /sbin/cryptsetup ]] ; then
        yad --title=$"Ошибка" --window-icon=error --center --borders=10 \
         --button=$"Продолжить без шифрования разделов":0 \
         --button=$"Выход":1 --text=$"Вам нужно установить cryptsetup и запустить команду 'sudo modprobe dm-mod', прежде чем вы сможете использовать шифрование."
        if [[ $? = 0 ]] ;  then
            encrypt_os="no"
            encrypt_home="no"
        else
            exit 1
        fi
    fi
    # end test for cryptsetup
fi    


## Partition a disk ##### 


list_disks () {

	env LC_ALL=C fdisk -l | egrep "^Disk|^/dev" > /tmp/diskinfo
	echo >> /tmp/diskinfo
	env LC_ALL=C blkid -c /dev/null >> /tmp/diskinfo
	cat /tmp/diskinfo | yad --text-info --title=Disks --borders=10  --width 550 --height 400 --button="Close":0 && rm -f /tmp/diskinfo &
}

partition_disk () {
if [ -n "$gpt_list" ] || [ "$uefi_boot" = yes ] ; then
	cli_partition_tool="gdisk"
else
	cli_partition_tool="cfdisk"
fi

yad --title=$"Разделение на разделы" --button=$"Run GParted":0 --button=$"Run $cli_partition_tool":1 \
    --width=650 --button=$"Пропустить этот шаг":2 --button=$"Выход":3 --center --borders=10 \
    --text=$"  Вам необходимо подготовить по крайней мере один раздел для установки, плюс по одному для каждого отдельного  
  раздела, который вы выбрали. Если у вас уже есть готовые раздел(ы), вы можете пропустить этот шаг.

  Запустить разделитель прямо сейчас?"

	ans="$?"
	case $ans in
		0) 	gparted ;;
		1)  xterm -T "Закройте этот терминал после разделения" -fa mono -fs 12 -geometry 90x25+0+0 -hold -e "$cli_partition_tool" ;;
		2)  ;;
		3) exit 0 ;;
	esac

}

#    # test to make sure there's a separate /boot partition
if [[ $sep_boot != "yes" ]]; then
    if [[ $encrypt_os = "yes" ]]; then   # ...do full disk encryption.
		encrypt_boot="yes"
        yad --window-icon=gtk-dialog-warning --title=$"Warning" --center --borders=10 \
         --button=$"Продолжать":0 \
         --button=$"Abort":1 --text=$"Ваш каталог /boot будет частью зашифрованной файловой системы, и для этого раздела будет использоваться формат \nluks1.\n\nВы можете продолжить, или вы можете выйти и начать все сначала, если вам нужен отдельный раздел для /boot."
		ans="$?"
		case $ans in
			0) ;;
			1) exit 0 ;;
		esac
    fi
fi


list_disks
partition_disk

ask_format_efi () {

yad --info --title=$"Формат EFI" --center --borders=10 \
	--button=$"Да":0 --button=$"Нет":1 --button=$"Выйти":2 \
	--text=$"ПРЕДУПРЕЖДЕНИЕ:  Выбранный раздел не содержит файловой системы FAT32.
 Если вы только что создали новый раздел efi (ef00), вам необходимо его отформатировать.  
 
	1) Да, создать файловую систему FAT32 на $esp_dev
	2) Нет, продолжайте без загрузчика.
	3) Прервите установку, чтобы исследовать ситуацию.
 
 Форматировать новый раздел EFI?:  "

	ans="$?"
 
	case "$ans" in
		0) mkfs.vfat -F 32 "$esp_dev" ;;
		1) ;;
		2) exit 0 ;;
	esac

}


choose_esp () {

	esp_info=$(env LC_ALL=C fdisk -l | awk '/EFI System/ { print $0 }')
#	esp_dev_list=$(env LC_ALL=C fdisk -l | awk '/EFI System/ { print $1 }')
	esp_count=$(env LC_ALL=C fdisk -l | awk '/EFI System/ { print $0 }' | wc -l)


	if [ "$esp_count" -eq 0 ] ; then
		esp_dev_message=$"Раздела EFI нет. Вам нужно будет создать его."
		yad --info --title=Error --borders=10 --text="$esp_dev_message" --image=gtk-dialog-error \
		--button="Разделитель":0 --button="Выйти":2
	ans="$?"

		case $ans in
			0) list_disks ; partition_disk ;;
			1) exit 0 ;;
		esac
	fi

	esp_dev=$(env LC_ALL=C fdisk -l | awk '/EFI System/ { print $1 }' | yad --list --title="Выберите раздел EFI" --center --borders=10 \
		--text=$"Выберите устройство для использования в качестве раздела EFI. Чтобы продолжить без загрузчика, нажмите ОК без выбора раздела.\n\n$esp_info\n" \
		--separator="" --column $'EFI Partitions' --height=180 --width=600 --button=$"OK":0 --button=$"Разделитель":1 --button=$"Выйти":2)
	ans="$?"
 
		case "$ans" in
			0) [ -n "$esp_dev" ] || return 0 ;;
			1) list_disks ; partition_disk ;;
			2) exit 0 ;;
		esac


	if ! blkid -c /dev/null -s TYPE "$esp_dev" | grep -q "vfat" ; then
		ask_format_efi
	fi

}

if [[ $must_choose_esp = "yes" ]] ; then
	choose_esp
fi


# Find hard drives, and choose one for grub
choose_grub () {

gpt_list=$(env LC_ALL=C fdisk -l | awk '/Disklabel type/ { print $3 }' | grep gpt)
bios_grub_dev=$(env LC_ALL=C fdisk -l | awk '/BIOS boot/ { print $1 }')
if [ -n "$gpt_list" ] && [ -z "$bios_grub_dev" ] ; then
	bios_boot_warning=$"\nПРЕДУПРЕЖДЕНИЕ. Загрузка с диска gpt завершится неудачно без загрузочного раздела BIOS.\n"
fi

yad --title=$"Установите загрузчик GRUB" --center --borders=10 --text=$"  Выберите место для установки загрузчика GRUB. Обычный выбор заключается в  
  поместите его в основную загрузочную запись первого жесткого диска (/dev/sda).  
${bios_boot_warning}
		Выберите MBR для установки на mbr любого жесткого диска. 
		Выберите Раздел для установки в раздел.
		Выберите Без загрузчика, чтобы продолжить работу без загрузчика. 
		Выберите Выход для выхода из этой программы.
		" \
--button=$"MBR":0 --button=$"Раздел":1 --button=$"Без загрузчика":2 --button=$"Выход":3
answer="$?"

if [[ $answer = 0 ]] ; then
grub_dev=$(find /dev -mindepth 1 -maxdepth 1  | egrep "*[shv]d[a-z]$|*nvme[0-9]n[0-9]$|*mmcblk[0-9]$" \
  | sort | awk '{print "\n" $0 }' \
  | yad --list --separator="" --title=$"Загрузчик" --center --borders=10 --text=$"Выберите место для установки загрузчика.
" \
  --column 'Hard Drives' --height=200)

	if [[ -z $grub_dev ]] ; then
		yad --title=$"Ошибка" --window-icon=error --center --borders=10 --button=$"Да, я уверен.":0 --button=$"Вернуться":1 \
	--text=$"Загрузчик не будет установлен. Вы уверены, что хотите этого?"
			if [[ $? = 1 ]] ; then
				choose_grub
			fi
	elif ! [[ -b $grub_dev ]] ; then
		yad --title=$"Ошибка"  --window-icon=error --center --borders=10 --button=$"Выйти":0 --button=$"Вернуться":1 \
	--text=$"Что-то не так.  $grub_dev не является блочным устройством."
			if [[ $? = 0 ]] ; then
				exit 1
			else
				choose_grub
			fi
	fi

elif [[ $answer = 1 ]] ; then
grub_partition=$(find /dev -mindepth 1 -maxdepth 1  | egrep  "*[shv]d[a-z][1-99]|*nvme[0-9]n[0-9]p[1-99]|*mmcblk[0-9]p[1-99]" \
  | sort | awk '{print "\n" $0 }' \
  | yad --list   --title=$"Загрузчик" --center --borders=10 --text=$"Выберите раздел для загрузчика (GRUB)." \
  --separator="" --column $'Partitions' --height=380 --width=150)

	if [[ -z $grub_partition ]] ; then
		yad --title=$"Ошибка" --window-icon=error --center --borders=10 --button=$"Да, я уверен.":0 --button=$"Вернуться":1 \
	--text=$"Загрузчик не будет установлен. Вы уверены, что хотите этого?"
			if [[ $? = 1 ]] ; then
				choose_grub
			fi
	elif ! [[ -b $grub_partition ]] ; then
		yad --title=$"Ошибка"  --window-icon=error --center --borders=10 --button=$"Выйти":0 --button=$"Вернуться":1 \
	--text=$"Что-то не так.  $grub_partition не является блочным устройством."
			if [[ $? = 0 ]] ; then
				exit 1
			else
				choose_grub
			fi
	fi


elif [[ $answer = 2 ]] ; then
	yad  --title=$"Загрузчик" --center --borders=10 --text=$"  Работа без загрузчика. 
  Вам нужно будет выполнить специальные действия для загрузки вашей операционной системы. 
  Быть уверенным  что ты знаешь, что делаешь." \
	--button=$"Proceed":0 --button=$"Exit":1
		if [[ $? = 1 ]] ; then
			exit 0
		fi
elif [[ $answer = 3 ]] ; then
	exit 0
fi
}

if [[ $uefi_boot = "yes" ]] ;then
	grub_dev="efi"
	if [[ -z "$esp_dev" ]] ; then
		grub_dev=""
	fi
elif [[ -z "$grub_package" ]] ; then  # grub_package is null if correct grub is installed.
	choose_grub
fi


# Show the partition list in a menu, and choose one for /boot
choose_boot () {
boot_dev=$(find /dev -mindepth 1 -maxdepth 1  | egrep  "*[shv]d[a-z][1-99]|*nvme[0-9]n[0-9]p[1-99]|*mmcblk[0-9]p[1-99]" \
  | sort | awk '{if ($0 != "'$esp_dev'") {print "\n" $0 }}' \
  | yad --list   --title=$"/boot partition" --center --borders=10 --text=$"Select a partition for /boot." \
  --separator="" --column ' ' --column $'Partitions' --height=380 --width=200 --button=$"OK":0)
boot_dev=$(echo $boot_dev | sed -e 's/(null)//')
}

if [[ $sep_boot = "yes" ]]; then
    choose_boot
fi

# Choose filesystem type for /boot
choose_fs_boot () {
if [[ -n $boot_dev ]]; then
     fs_type_boot=$(yad --list --title=$"/boot filesystem" --center --borders=10 --text=$"Какой тип файловой системы вы бы хотели $boot_dev?" \
  --separator="" --column $"Format" --height=200 --button=$"OK":0 \
  "ext4" \
  "ext3" \
  "ext2")
fi

if [[ -z $fs_type_boot ]]; then
    yad --window-icon=error --title=$"Ошибка" --center --borders=10 --button=$"Вернуться":0 --button=$"Выйти":1 \
      --text=$"Вы должны выбрать тип файловой системы для /boot"
    if [[ $? = 0 ]]; then
        choose_fs_boot
    else
        exit 1
    fi
fi
}

if [[ -n $boot_dev ]]; then
	if [[ $no_format = "yes" ]]; then 
		fs_type_boot=$(blkid -s TYPE "$boot_dev" | awk -F"\"" '{ print $2 }')
	else
		choose_fs_boot
	fi
fi


# Show the partition list in a menu, and choose one for the OS
choose_root () {
install_dev=$(find /dev -mindepth 1 -maxdepth 1  | egrep  "*[shv]d[a-z][1-99]|*nvme[0-9]n[0-9]p[1-99]|*mmcblk[0-9]p[1-99]" \
  | sort | awk '{if ($0 != "'$esp_dev'") {print "\n" $0 }}' \
  | yad --list --title=$"Root Раздел" --center --borders=10 --text=$"Выберите раздел, который будет использоваться для установки операционной системы." \
    --separator="" --column ' ' --column $'Partitions' --height 380 --width 200 --button=$"OK":0)
install_dev=$(echo $install_dev | sed -e 's/(null)//')

if [[ -z $install_dev ]] ; then
    yad --window-icon=error --title=$"Ошибка" --center --borders=10 --button=$"Вернуться":0 --button=$"Выйти":1 \
  --text=$"Ничего не было выбрано. Вы должны выбрать раздел для установки. Чем бы Вы хотели заняться?"
        if [[ $? = 0 ]] ; then
            choose_root
        else
            exit 1
        fi
elif ! [[ -b $install_dev ]] ; then
    yad --window-icon=error --title=$"Ошибка" --center --borders=10 --button=$"Вернуться":0 --button=$"Выйти":1 \
  --text=$"    Что-то не так. Может быть, вы проверили
     более одной коробки. Вы сказали, что хотите установить
     систему на $install_dev"
        if [[ $? = 0 ]] ; then
            choose_root
        else
            exit 1
        fi
elif
    [[ $install_dev = $boot_dev ]] ; then
    yad --window-icon=error --title=$"Ошибка" --center --borders=10 --text=$"Вы выбрали тот же раздел для операционной системы, что и для /boot. Попробуйте снова." --button=$"OK":0
        choose_root
fi
}

choose_root


# Choose filesystem type for OS.
choose_fs_os () {
fs_type_os=$(yad --list --title=$"Root Файловая система" --center --borders=10 --text=$"Какой тип файловой системы вы бы хотели $install_dev?" \
  --separator="" --column $"Format" --height=200 --button=$"OK":0 \
  "ext4" \
  "ext3" \
  "ext2")
if [[ -z $fs_type_os ]]; then
        yad --window-icon=error --title=$"Ошибка" --center --borders=10 --button=$"Вернуться":0 --button=$"Выйти":1 \
      --text=$"Вы должны выбрать тип файловой системы
для операционной системы"
    if [[ $? = 0 ]]; then
        choose_fs_os
    else
        exit 1
    fi
fi  
}

if [[ $no_format = "yes" ]]; then 
	fs_type_os=$(blkid -s TYPE "$install_dev" | awk -F"\"" '{ print $2 }')
else
	choose_fs_os
fi


# Show the partition list in a menu, and choose one for /home
choose_home () {
home_dev=$(find /dev -mindepth 1 -maxdepth 1  | egrep  "*[shv]d[a-z][1-99]|*nvme[0-9]n[0-9]p[1-99]|*mmcblk[0-9]p[1-99]" \
  | sort | awk '{if ($0 != "'$esp_dev'") {print "\n" $0 }}' \
  | yad --list --title=$"/home partition" --center --borders=10 --text=$"Выберите раздел для /home" \
  --separator="" --column ' ' --column $'Partitions' --height=380 --width=200 --button=$"OK":0)
home_dev=$(echo $home_dev | sed -e 's/(null)//')

if [[ -n $home_dev ]] ; then
    if ! [[ -b $home_dev ]] ; then
        yad --info --title="Ошибка" --center --borders=10 --button=$"Вернуться":0 --button=$"Выйти":1 \
        --text=$"    Что-то не так. 
    $home_dev не является блочным устройством. "
        if [[ $? = 0 ]] ; then
            choose_home
        else
            exit 1
        fi
    elif
        [[ $install_dev = $home_dev ]] ; then
        yad --window-icon=error --title=$"Ошибка" --center --borders=10 --text=$"Вы выбрали тот же раздел для /home, что и для операционной системы. Если вам не нужен отдельный /home раздел, нажмите OK, не выбирая ни один." \
         --button=$"Вернуться":0 --button=$"Выйти":1
        if [[ $? = 0 ]] ; then
            choose_home
        else
            exit 1
        fi
    elif
        [[ $boot_dev = $home_dev ]] ; then
        yad --window-icon=error --title=$"Ошибка" --center --borders=10 --text=$"Вы выбрали тот же раздел для /home как один для /boot. Попробуй еще раз." \
         --button=$"Вернуться":0 --button=$"Выйти":1
        if [[ $? = 0 ]] ; then
            choose_home
        else
            exit 1
        fi
    fi
fi
}

if [[ $sep_home = "yes" ]]; then
    choose_home
fi


# Choose filesystem type for /home
choose_fs_home () {
if [[ -n $home_dev ]]; then
     fs_type_home=$(yad --list --title=$"/home файловая система" --center --text=$"Какой тип файловой системы вы бы хотели $home_dev?" \
  --separator="" --column $"Format" --height=200 --button=$"OK":0 \
  "ext4" \
  "ext3" \
  "ext2")
fi

if [[ -z $fs_type_home ]]; then
    yad --window-icon=error --title=$"Ошибка" --center --borders=10 --button=$"Вернуться":0 --button=$"Выйти":1 \
      --text=$"Вы должны выбрать тип файловой системы для /home"
    if [[ $? = 0 ]]; then
        choose_fs_home
    else
        exit 1
    fi
fi
}

if [[ -n $home_dev ]]; then
	if [[ $no_format = "yes" ]] ; then    #|| [[ $keep_old_home = "yes" ]] ; then 
		fs_type_home=$(blkid -s TYPE "$home_dev" | awk -F"\"" '{ print $2 }')
#	elif [[ -z $keep_old_home ]] ; then
	else
		choose_fs_home
	fi
fi


# Show available swap partitions and choose one.
choose_swap () {
swap_info=$(/sbin/blkid |grep swap | awk '{if ($0 != "'$esp_dev'") {print "\n" $0 }}' \
| yad --list   --title=$"swap раздел" --center --borders=10 --text=$"Выберите раздел для swap." \
  --separator="" --column $'Partitions' --height=180 --width=600 --button=$"OK":0)
swap_dev=$(echo $swap_info | awk -F: '{ print $1 }')

if [[ -z $swap_dev ]] ; then
	yad --window-icon=error --title=$"Ошибка" --center --borders=10 --text=$"Вы не выбрали раздел подкачки.
Нажмите кнопку ОК, чтобы вместо этого использовать файл подкачки.
Нажмите Отмена, чтобы выйти из программы."
        if [[ $? = 0 ]] ; then
            use_existing_swap=""
        else
            exit 1
        fi
fi
}


if [[ $use_existing_swap = "yes" ]]; then
    choose_swap
fi




# Show a summary of what will be done

if [[ $grub_dev = "efi" ]] || [[ -n "$grub_package" ]] ; then
	grub_dev_message=$"--> О загрузчике вас спросят позже."
elif [[ -n $grub_dev ]] ; then
    grub_dev_message=$"--> Загрузчик будет установлен в $grub_dev"
elif [[ -n $grub_partition ]] ; then
	grub_dev_message=$"--> Загрузчик будет установлен в $grub_partition"
else
    grub_dev_message=$"--> Загрузчик не будет установлен."
fi

if [[ -n "$esp_dev" ]] ; then
	grub_dev_message=$"-->EFI раздел в $esp_dev"
fi

if [[ $encrypt_os = yes ]] ; then
    os_enc_message=$", и будет зашифрован."
fi

if [[ -z $home_dev ]] ; then
    home_dev_message=$"--> /home не будет на отдельном разделе."
elif [[ $no_format = "yes" ]] ; then
	home_dev_message=$"--> /home будет установлен на $home_dev без его форматирования."
else
    home_dev_message=$"--> /home будет установлен на $home_dev и отформатирован как $fs_type_home"
fi

if [[ -n $home_dev ]] && [[ $encrypt_home = yes ]] ; then
    home_enc_message=$", и будет зашифрован."
fi

if [[ -n $boot_dev ]] ; then
	if [[ $no_format != "yes" ]]; then
		boot_dev_message=$"--> /boot будет установлен на $boot_dev и отформатирован как $fs_type_boot."
	else
		boot_dev_message=$"--> /boot будет установлен на $boot_dev"
	fi
fi

#if [[ $encrypt_os = yes ]] || [[ $encrypt_home = yes ]] ; then
    proceed_message=$"*** Если кажется, что установщик остановился, проверьте терминал на наличие сообщений. ***"
#fi

if [[ $disable_auto_desktop = "yes" ]]; then
	desktop_message=$"Настольный автологин будет отключен."
fi

if [[ $disable_auto_console = "yes" ]]; then
	console_message=$"Консоль автологина будет отключена."
fi

if [[ $no_format = "yes" ]]; then
	install_dev_message=$"--> Операционная система будет установлена на $install_dev без форматирования его."
else
	install_dev_message=$"-->Операционная система будет установлена на $install_dev и отформатирован как $fs_type_os"
fi

if [[ $run_preinstall = "yes" ]] ; then
	preinstall_message=$"предустановочные скрипты включены."
else
	preinstall_message=$"предустановочные скрипты отключены."	
fi
if [[ $run_postinstall = "yes" ]] ; then
	postinstall_message=$"сценарии после установки включены."
else
	postinstall_message=$"сценарии после установки отключены."	
fi


yad --info --title=$"Резюме" --center --borders=10 --button=$"Продолжить установку.":0 --button=$"Выйти":1 \
    --text=$"Пожалуйста, закройте все запущенные приложения сейчас.

Вот краткое изложение того, что будет сделано. ЭТО ВАШ ПОСЛЕДНИЙ ШАНС ВЫЙТИ перед установкой системы.

$grub_dev_message
$install_dev_message$os_enc_message
$home_dev_message$home_enc_message
$boot_dev_message
$desktop_message
$console_message
$uuid_message
$disklabel_message
$preinstall_message
$postinstall_message
$separate_partition_message

$proceed_message"
    if [[ $? != "0" ]] ; then
        exit 0
    fi


# Actual installation begins here


# Run pre-install scripts if enabled.
if [[ $run_preinstall = "yes" ]] ; then
	for file in /usr/lib/refractainstaller/pre-install/* ; do
		if [[ -x $file ]] ; then
			bash $file
		fi
	done
fi


# Unmount or close anything that might need unmounting or closing
cleanup () {
echo -e $"\n @@@ Cleaning up...\n" >> "$error_log"
if $(df | grep -q /target/proc/) ; then
    umount /target/proc/
fi

if $(df | grep -q /target/dev/) ; then
    umount /target/dev/
fi

if $(df | grep -q /target/sys/) ; then
    umount /target/sys/
fi

if $(df | grep -q $esp_dev) ; then
	umount $esp_dev
fi

# grep gives an error if $boot_dev is null
if $(df | grep -q $boot_dev) ; then
    umount -l $boot_dev
fi

if $(df | grep -q /target_boot/efi) ; then
    umount -l /target_boot/efi
fi

if $(df | grep -q /target_boot) ; then
    umount -l /target_boot/
fi

if $(df | grep -q /target_home) ; then
    umount -l /target_home/
fi

# grep gives an error if $home is null
if $(df | grep -q $home_dev) ; then
    umount $home_dev
fi

if $(df | grep -q "\/dev\/mapper\/home_fs") ; then
    umount /dev/mapper/home_fs
fi

if [[ -h /dev/mapper/home_fs ]] ; then
    cryptsetup luksClose home_fs
fi

if $(df | grep -q /target) ; then
    umount -l /target/
fi

if $(df | grep -q $install_dev) ; then
    umount $install_dev
fi    

if $(df | grep "\/dev\/mapper\/root_fs") ; then
    umount /dev/mapper/root_fs
fi

if [[ -h /dev/mapper/root_fs ]] ; then
    cryptsetup luksClose /dev/mapper/root_fs
fi

# These next ones might be unnecessary
if [[ -d /target ]] ; then
    rm -rf /target
fi

if [[ -d /target_home ]] ; then
    rm -rf /target_home
fi

if [[ -d /target_boot ]] ; then
    rm -rf /target_boot
fi
}

cleanup | tee >(yad --progress --pulsate --width=350 --auto-close --title=$"Cleanup")


# Write random data or zeros to OS and /home partitions
# Redirect stderr so we can see the output of dd

if [[ $write_random = "yes" ]]; then
    if [[ $encrypt_os = "yes" ]]; then      
		exec 2>&1
        dd if=/dev/urandom of="$install_dev"
        exec 2>>"$error_log"
    fi  
fi

if [[ $write_random = "yes" ]]; then
    if [[ $encrypt_home = "yes" ]]; then
		exec 2>&1
        dd if=/dev/urandom of="$home_dev"
        exec 2>>"$error_log"
    fi  
fi

if [[ $write_zero = "yes" ]]; then
    dd if=/dev/zero of="$install_dev"
    if [[ $sep_home = "yes" ]] ; then   #&& [[ -z $keep_old_home ]] ; then
		exec 2>&1
        dd if=/dev/zero of="$home_dev"
        exec 2>>"$error_log"
    fi
    if [[ $sep_boot = "yes" ]]; then
		exec 2>&1
        dd if=/dev/zero of="$boot_dev"
        exec 2>>"$error_log"
    fi
fi


# make mount point, format, adjust reserve and mount
# install_dev must maintain the device name for cryptsetup
# install_part will be either device name or /dev/mapper name as needed.
mkdir /target ;  check_exit


#*****************************************************************************


make_luks () {
exec 2>/dev/null
	setpass=$(yad --form --field="Password:H" --field="Retype Password:H" --separator="@_@" \
	--title $"Passphrase" --center --borders=10 --image="dialog-password" --button=$"OK":0 --text=$"Введите кодовую фразу для зашифрованного тома: $mapper_name  \nUse TAB поменять поля.")

	if [[ $(echo $setpass  | awk -F"@_@" '{print $1}') != $(echo $setpass | awk -F"@_@" '{print $2}') ]] ; then
		try_again
		return
	else
		passphr=$(echo $setpass | awk -F"@_@" '{ print $1 }')
		if [[ $encrypt_boot = "yes" ]] ; then
			echo "$passphr" | cryptsetup luksFormat --type luks1 "$luks_dev"
		else
			echo "$passphr" | cryptsetup luksFormat "$luks_dev"
		fi
		echo "$passphr" | cryptsetup luksOpen "$luks_dev" "$mapper_name"
		 
	fi
exec 2>>"$error_log"
}


try_again () {
yad --image="gtk-dialog-warning" --title $"Ошибка" --center --borders=10 --button=$"Yes":0 --button=$"Выйти":1 \
--text=$"Записи не совпадают. Вы хотите попробовать еще раз?\nUse TAB поменять поля."
if [[ $? = 0 ]] ; then
	make_luks
else
	cleanup
	exit 0
fi
}


if [[ $encrypt_os = yes ]] ; then
	luks_dev="$install_dev"
	mapper_name="root_fs"
	make_luks
	install_part="/dev/mapper/$mapper_name"
else
    install_part="$install_dev"
fi 
if [[ $no_format != "yes" ]]; then
	mke2fs -t $fs_type_os "$install_part"  # ; check_exit 
fi
mount "$install_part" /target ; check_exit 


# make mount point for separate home if needed
# and set variable for rsync exclusion.
if [[ -n $home_dev ]]; then
    mkdir /target_home ; check_exit
    if [[ $encrypt_home = yes ]]; then
		luks_dev="$home_dev"
		mapper_name="home_fs"
		make_luks
        home_part="/dev/mapper/$mapper_name"
    else
        home_part=$home_dev
	fi
	if [[ $no_format != "yes" ]] ; then   #&& [[ -z $keep_old_home ]] ; then
		mke2fs -t $fs_type_home "$home_part" # ; check_exit
	fi
#	if [[ -z $keep_old_home ]] ; then
	mount "$home_part" /target_home ; check_exit
#	fi
	sep_home_opt="--exclude=/home/*"
fi



#*****************************************************************************


# make mount point for separate /boot if needed
# and set variable for rsync exclusion.
# allow default for reserved blocks (don't need tune2fs here)
if [[ -n $boot_dev ]] ; then
    mkdir /target_boot ; check_exit
    if [[ $no_format != "yes" ]]; then
		mke2fs -t $fs_type_boot $boot_dev # ; check_exit
	fi
    mount $boot_dev /target_boot
    sep_boot_opt="--exclude=/boot/*"
fi


# copy everything over except the things listed in the exclude list
rsync -av / /target/ --filter='P lost+found' --filter='H lost+found' --exclude-from="$rsync_excludes" ${sep_home_opt} ${sep_boot_opt} | \
tee >(yad --progress --pulsate --width=350 --auto-close --title=$"Копирование системы в новый раздел.")


# copy separate /home if needed
if [[ -n $home_dev ]] ; then   #&& [[ -z $keep_old_home ]] ; then
    rsync -av /home/ /target_home/ --filter='P lost+found' --filter='H lost+found' --exclude-from="$home_boot_excludes" | \
tee >(yad --progress --pulsate --width=350 --auto-close --title=$"Копирование домашних папок в новый раздел.")
fi

# copy separate /boot if needed
if [[ -n $boot_dev ]] ; then
    rsync -av /boot/ /target_boot/ --filter='P lost+found' --filter='H lost+found' --exclude-from="$home_boot_excludes" | \
tee >(yad --progress --pulsate --width=350 --auto-close --title=$"Копирование файлов в загрузочный раздел.")
fi

#*************************************************************

# make some basic entries in /dev so the system can boot properly before udev starts

mknod -m 622 /target/dev/console c 5 1
mknod -m 666 /target/dev/null c 1 3
mknod -m 666 /target/dev/zero c 1 5
mknod -m 666 /target/dev/ptmx c 5 2
mknod -m 666 /target/dev/tty c 5 0
mknod -m 444 /target/dev/random c 1 8
mknod -m 444 /target/dev/urandom c 1 9
chown -v root:tty /target/dev/{console,ptmx,tty}

ln -sv /proc/self/fd /target/dev/fd
ln -sv /proc/self/fd/0 /target/dev/stdin
ln -sv /proc/self/fd/1 /target/dev/stdout
ln -sv /proc/self/fd/2 /target/dev/stderr
ln -sv /proc/kcore /target/dev/core
ln -sv /run/shm /target/dev/shm
mkdir -v /target/dev/pts

#*************************************************************

# create swapfile
if ! [[ $use_existing_swap = "yes" ]] ; then
	dd if=/dev/zero of=/target/swapfile bs="$swapfile_blocksize" count="$swapfile_count" | \
	tee >(yad --progress --pulsate --width=350 --auto-close --center --title=$"Сделать файл подкачки...")
	mkswap /target/swapfile ; check_exit 
	chmod 600 /target/swapfile
fi


# Disallow mounting of all fixed drives with pmount
if [[ -f /target/etc/pmount.allow ]] ; then
	if [[ $pmount_fixed = "no" ]] ; then
		sed -i 's:/dev/sd\[a-z\]:#/dev/sd\[a-z\]:' /target/etc/pmount.allow
	fi
fi

# Re-enable updatedb if it was disabled by an older version of refractasnapshot
if [[ -e /target/usr/bin/updatedb.mlocate ]] ; then
	if ! [[ -x /target/usr/bin/updatedb.mlocate ]] ; then
		chmod +x /target/usr/bin/updatedb.mlocate
	fi
fi


# Disable autologin
set_noautologin_desktop () {

	#gdm
    if [[ -f /target/etc/gdm/gdm.conf ]]; then
        sed -i 's/^AutomaticLogin/#AutomaticLogin/' /target/etc/gdm/gdm.conf
    fi

	#gdm3
    if [[ -f /target/etc/gdm3/daemon.conf ]]; then
        sed -i 's/^AutomaticLogin/#AutomaticLogin/' /target/etc/gdm3/daemon.conf
    fi

	#lightdm
	if [[ -f /target/etc/lightdm/lightdm.conf ]]; then
		sed -i 's/^autologin/#autologin/g' /target/etc/lightdm/lightdm.conf
	fi

	#kdm
	if [ -f /target/etc/default/kdm.d/live-autologin ]; then
		rm -f /target/etc/default/kdm.d/live-autologin
	fi

	if [ -f /target/etc/kde3/kdm/kdmrc ]; then
		sed -i -e 's/^AutoLogin/#AutoLogin/g' /target/etc/kde3/kdm/kdmrc \
			-e 's/^AutoReLogin/#AutoReLogin/g' /target/etc/kde3/kdm/kdmrc
	fi

	if [ -f /target/etc/kde4/kdm/kdmrc ]; then
		sed -i -e 's/^AutoLogin/#AutoLogin/g' /target/etc/kde4/kdm/kdmrc \
			-e 's/^AutoReLogin/#AutoReLogin/g' /target/etc/kde4/kdm/kdmrc
	fi

	# trinity desktop

	# v3.5.13
	if [[ -f /target/etc/default/kdm-trinity.d/live-autologin ]]; then
		rm -f  /target/etc/default/kdm-trinity.d/live-autologin
	fi

	if [ -f /target/etc/trinity/kdm/kdmrc ]; then
		sed -i -e 's/^AutoLogin/#AutoLogin/g' /target/etc/trinity/kdm/kdmrc \
			-e 's/^AutoReLogin/#AutoReLogin/g' /target/etc/trinity/kdm/kdmrc
	fi

	# v3.5.14
	if [[ -f /target/etc/default/tdm-trinity.d/live-autologin ]]; then
		rm -f  /target/etc/default/tdm-trinity.d/live-autologin
	fi

	if [ -f /target/etc/trinity/tdm/tdmrc ]; then
		sed -i -e 's/^AutoLogin/#AutoLogin/g' /target/etc/trinity/tdm/tdmrc \
			-e 's/^AutoReLogin/#AutoReLogin/g' /target/etc/trinity/tdm/tdmrc
		
	fi

	#slim
	if [[ -f /target/etc/slim.conf ]] ; then
		sed -i -e 's/^[ ]*default_user/#default_user/' \
			-e 's/^[ ]*auto_login.*$/#auto_login no/' /target/etc/slim.conf
	fi

	# lxdm
	if [[ -f /target/etc/lxdm/lxdm.conf ]] ; then
		sed -i -e 's/^autologin=/#autologin=/' /target/etc/lxdm/lxdm.conf
	fi

	# No display manager
	if [ -f /target/etc/profile.d/zz-live-config_xinit.sh ]; then
		rm -f /target/etc/profile.d/zz-live-config_xinit.sh
	fi

}


# Keep autologin and update username in the display manager config.
set_autologin_desktop () {

	#gdm
    if [[ -f /target/etc/gdm/gdm.conf ]]; then
        sed -i "/AutomaticLogin/s/$oldusername/$newusername/" /target/etc/gdm/gdm.conf
    fi

	#gdm3
    if [[ -f /target/etc/gdm3/daemon.conf ]]; then
        sed -i "/AutomaticLogin/s/$oldusername/$newusername/" /target/etc/gdm3/daemon.conf
    fi

	#lightdm
	if [[ -f /target/etc/lightdm/lightdm.conf ]]; then
		sed -i "/autologin/s/=$oldusername/=$newusername/" /target/etc/lightdm/lightdm.conf
	fi

	#kdm
	if [ -f /target/etc/default/kdm.d/live-autologin ]; then
		# This one might not be right.
		sed -i "s/$oldusername/$newusername/g" /target/etc/default/kdm.d/live-autologin
	fi

	if [ -f /target/etc/kde3/kdm/kdmrc ]; then
		sed -i -e "/AutoLogin/s/$oldusername/$newusername/" /target/etc/kde3/kdm/kdmrc \
			-e "/AutoReLogin/s/$oldusername/$newusername/" /target/etc/kde3/kdm/kdmrc
	fi

	if [ -f /target/etc/kde4/kdm/kdmrc ]; then
		sed -i -e "/AutoLogin/s/$oldusername/$newusername/" /target/etc/kde4/kdm/kdmrc \
			-e "/AutoReLogin/s/$oldusername/$newusername/" /target/etc/kde4/kdm/kdmrc
	fi

	# trinity desktop
	
	# v3.5.13
	if [[ -f /target/etc/default/kdm-trinity.d/live-autologin ]]; then
		# This one might not be right.
		sed -i "s/$oldusername/$newusername/g" /target/etc/default/kdm-trinity.d/live-autologin
	fi

	if [ -f /target/etc/trinity/kdm/kdmrc ]; then
		sed -i -e "/AutoLogin/s/$oldusername/$newusername/" /target/etc/trinity/kdm/kdmrc \
			-e "/AutoReLogin/s/$oldusername/$newusername/" /target/etc/trinity/kdm/kdmrc	
	fi

	# v3.5.14
	if [[ -f /target/etc/default/tdm-trinity.d/live-autologin ]]; then
		# This one might not be right.
		sed -i "s/$oldusername/$newusername/g" /target/etc/default/tdm-trinity.d/live-autologin		
	fi

	if [ -f /target/etc/trinity/tdm/tdmrc ]; then
		sed -i -e "/AutoLogin/s/$oldusername/$newusername/" /target/etc/trinity/tdm/tdmrc \
			-e "/AutoReLogin/s/$oldusername/$newusername/" /target/etc/trinity/tdm/tdmrc		
	fi

	#slim
	if [[ -f /target/etc/slim.conf ]] ; then
		sed -i  -e "/default_user/s/\s\+$oldusername/ $newusername/" /target/etc/slim.conf
	fi

	# lxdm
	if [[ -f /target/etc/lxdm/lxdm.conf ]] ; then
		sed -i -e "/^autologin=/s/$oldusername/$newusername/" /target/etc/lxdm/lxdm.conf
	fi

	# No display manager
    # (Nothing to do here.)
    
}


# setup fstab

# add entry for root filesystem
if [[ $encrypt_os != "yes" ]]; then
	if [[ $use_uuid = yes ]]; then
		install_part="$(blkid -s UUID $install_dev | awk '{ print $2 }' | sed 's/\"//g')"
	elif [[ $use_labels = yes ]]; then
			rootfslabel=$(/sbin/blkid -c /dev/null -s LABEL $install_dev | awk -F"\"" '{ print $2 }')
			if [[ -n $rootfslabel ]]; then
				install_part="LABEL=$rootfslabel"
			else
				rootfslabel=$(yad  --entry --title=$"Метка файловой системы"  --center --borders=10 --text=$"Введите метку диска для $install_dev" --width=300 --button=$"OK":0)
				if [[ -n $rootfslabel ]]; then
					e2label "$install_dev"  "$rootfslabel"
					install_part="LABEL=$rootfslabel"
				else
					install_part="$install_dev"
				fi
			fi
	else
		install_part="$install_dev"
	fi
fi
echo -e "$install_part\t/\t$fs_type_os\tdefaults,noatime\t0\t1" > /target/etc/fstab
check_exit


# add entry for /home to fstab if needed
if ! [[ -z $home_dev ]] ; then
	if [[ $encrypt_home != "yes" ]]; then
		if [[ $use_uuid = yes ]]; then
			home_part="$(blkid -s UUID $home_dev | awk '{ print $2 }' | sed 's/\"//g')"
		elif [[ $use_labels = yes ]]; then
				homefslabel=$(/sbin/blkid -c /dev/null -s LABEL $home_dev | awk -F"\"" '{ print $2 }')
				if [[ -n $homefslabel ]]; then
					home_part="LABEL=$homefslabel"
				else
					homefslabel=$(yad  --entry --title=$"Метка файловой системы"  --center --borders=10 --text=$"Введите метку диска для $home_dev" --width=300 --button=$"OK":0)
					if [[ -n $homefslabel ]]; then
						e2label "$home_dev"  "$homefslabel"
						home_part="LABEL=$homefslabel"
					else
						home_part="$home_dev"
					fi
				fi
		else
			home_part="$home_dev"
		fi

	fi
    echo -e "$home_part\t/home\t$fs_type_home\tdefaults,noatime\t0\t2" >> /target/etc/fstab
    check_exit
fi

# add entry for /boot to fstab if needed
if [[ -n $boot_dev ]] ; then
	if [[ $use_uuid = yes ]]; then
		boot_part="$(blkid -s UUID $boot_dev | awk '{ print $2 }' | sed 's/\"//g')"
	elif [[ $use_labels = yes ]]; then
			bootfslabel=$(/sbin/blkid -c /dev/null -s LABEL $boot_dev | awk -F"\"" '{ print $2 }')
			if [[ -n $bootfslabel ]]; then
				boot_part="LABEL=$bootfslabel"
			else
				bootfslabel=$(yad  --entry --title=$"Метка файловой системы"  --center --borders=10 --text=$"Введите метку диска для $boot_dev" --width=300 --button=$"OK":0)
				if [[ -n $bootfslabel ]]; then
					e2label "$boot_dev"  "$bootfslabel"
					boot_part="LABEL=$bootfslabel"
				else
					boot_part="$boot_dev"
				fi
			fi
	else
		boot_part="$boot_dev"
	fi
    echo -e "$boot_part\t/boot\t$fs_type_boot\tdefaults,noatime,\t0\t2" >> /target/etc/fstab
    check_exit
fi


# add entry for swap to fstab if needed
if [[ $use_existing_swap = "yes" ]] ; then
	if [[ $use_uuid = yes ]]; then
		swap_part="$(/sbin/blkid -s UUID $swap_dev | awk '{ print $2 }' | sed 's/\"//g')"
	else
		swap_part="$swap_dev"
	fi
    echo -e $"\n Adding swap entry to fstab...\n"
    echo -e "$swap_part\tnone\tswap\tsw\t0\t0" >> /target/etc/fstab
else
	echo -e "/swapfile\tnone\tswap\tsw\t0\t0" >> /target/etc/fstab
fi


# Add entry for root filesystem to crypttab if needed
if [[ $encrypt_os = yes ]] ; then
	if [[ $use_uuid = yes ]]; then
		install_crypt="$(blkid -s UUID $install_dev | awk '{ print $2 }' | sed 's/\"//g')"
		echo -e "root_fs\t\t$install_crypt\t\tnone\t\tluks" >> /target/etc/crypttab
	else
		echo -e "root_fs\t\t$install_dev\t\tnone\t\tluks" >> /target/etc/crypttab
	fi
fi


# Add entry for /home to crypttab if needed
if [[ $encrypt_home = yes ]] ; then
		if [[ $use_uuid = yes ]]; then
			home_crypt="$(blkid -s UUID $home_dev | awk '{ print $2 }' | sed 's/\"//g')"
			echo -e "home_fs\t\t$home_crypt\t\tnone\t\tluks" >> /target/etc/crypttab
		else
			echo -e "home_fs\t\t$home_dev\t\tnone\t\tluks" >> /target/etc/crypttab
		fi
fi

#####  May need to check for /etc/default/grub and warn if absent ##########
# Tell grub to use encrypted /boot directory.
if [[ $encrypt_boot = yes ]] ; then
	if ! [[ $(grep ^GRUB_ENABLE_CRYPTODISK /target/etc/default/grub) ]] ; then
		echo -e "\nGRUB_ENABLE_CRYPTODISK=y\n" >> /target/etc/default/grub
	fi
	if ! [[ $(grep 'UMASK=0077' /etc/initramfs-tools/conf.d/initramfs-permissions) ]] ; then
		echo -e '\nUMASK=0077\n' > /etc/initramfs-tools/conf.d/initramfs-permissions
	fi
fi


# Allow users to login to ssh with passwords if desired.
# Allow root login only with auth keys.
# or do nothing.
if [[ $ssh_pass = "yes" ]] ; then
	sed -i~ 's/PasswordAuthentication no/PasswordAuthentication yes/' /target/etc/ssh/sshd_config
	sed -i 's/PermitRootLogin yes/PermitRootLogin prohibit-password/' /target/etc/ssh/sshd_config
elif [[ $ssh_pass = "no" ]] ; then
	sed -i~ 's/.*PasswordAuthentication yes/PasswordAuthentication no/' /target/etc/ssh/sshd_config
	sed -i 's/PermitRootLogin yes/PermitRootLogin prohibit-password/' /target/etc/ssh/sshd_config
elif [[ -n "$ssh_pass" ]] ; then	
	echo $"WARNING: ssh_pass value not recognized. No changes were made to /etc/ssh/sshd_config"
fi


# mount stuff so grub will behave (so chroot will work)
mount --bind /dev/ /target/dev/ ; check_exit 
mount --bind /proc/ /target/proc/ ; check_exit 
mount --bind /sys/ /target/sys/ ; check_exit 




# Test for uefi readiness, choose esp if needed, add to fstab.



if [[ -n "$esp_dev" ]] ; then
	uefi_ready="yes"
fi

# add entry for esp_dev to fstab if needed
if [[ $uefi_ready = "yes" ]] && [[ $uefi_boot = "yes" ]] ; then

	if [[ $use_uuid = "yes" ]]; then
		esp_part="$(/sbin/blkid -s UUID $esp_dev | awk '{ print $2 }' | sed 's/\"//g')"
	else
		esp_part="$esp_dev"
	fi
	
	if [[ -n $boot_dev ]] ; then
		mount $boot_dev /target/boot
	fi
	
    echo -e $"\n Adding esp entry to fstab...\n"
    echo -e "$esp_part\t/boot/efi\tvfat\tumask=0077\t0\t1" >> /target/etc/fstab
	mkdir /target/boot/efi
	mount "$esp_dev" /target/boot/efi/
fi


#***********************************************************************

# Install (or not) grub


 
install_grub () {
# Setup GRUB 
echo $"Настройка загрузчика grub .. Пожалуйста, подождите .."

# If /boot is separate partition, need to mount it in chroot for grub
if [[ -n $boot_dev ]] ; then
    chroot /target mount $boot_dev /boot
fi


# If grub is installed to a partition, we need to know if it's grub-pc
# or grub-legacy/grub-gfx to handle it properly.
if [[ -n $grub_partition ]] ; then
	if [[ $grubversion != "grub-pc" ]] ; then

		# isolate the device (sdx) letter then use tr like this to translate to the right number for grub
		GRUBDEVICENUM=$(echo $grub_partition |sed 's:/dev/sd::' |sed 's:[0-9]::'g |tr '[a-j]' '[0-9]')

		# isolate the partition number
		INSTALLPARTNUM=$(echo $grub_partition |sed 's:/dev/sd::'|sed 's:[a-z]::')

		# and reduce it by 1 for grub
		GRUBPARTNUM=$(expr $INSTALLPARTNUM - 1)

		# finally get the finished grub root syntax
		GRUBROOT="(hd$GRUBDEVICENUM,$GRUBPARTNUM)"


		chroot /target grub-install $grub_partition
		grub --batch <<EOF
		root $GRUBROOT
		setup $GRUBROOT
		quit
EOF

	else
		error_message=$"установка grub не удалась."
		chroot /target grub-install --recheck --no-floppy --force $grub_partition >> "$error_log" ; check_exit
	fi

elif [[ $grub_dev = "efi" ]] ; then
	chroot /target grub-install ${efi_name_opt} ${media_opt} >> "$error_log"; check_exit

elif [[ -n $grub_dev ]]; then
    echo -e $"\n Installing the boot loader...\n"
    chroot /target grub-install $grub_dev >> "$error_log"; check_exit
fi

chroot /target update-grub ; check_exit

error_message=""
}


copy_grub_packages () {

	find "$grub_package_dir" -maxdepth 1 -name "$grub_package" -exec cp {} /target \;
#	chroot /target find . -name $grub_package -maxdepth 1 -exec dpkg -i {} \; # this works, but grub-pc/grub-pc-bin installed out of order.
if [[ -n "$grub_package" ]] ; then
	chroot /target /bin/bash -c "dpkg -i $grub_package"    # This works. They installed in right order.
fi
	if [[ "$grub_package" =~ grub-pc ]] ; then
		grubversion="grub-pc"
		choose_grub
	fi
	if [[ "$grub_package" =~ grub-efi ]] ; then
		grubversion="grub-efi"
		grub_dev="efi"
	fi
	install_grub
}


chroot_terminal () {

xterm -fa mono -fs 12 -geometry 90x20+0+0 -e 'chroot /target'

}


if [[ -n "$grub_package" ]] ; then
	grub_button=$"--button=Copy files:4"    # Do not translate "button".
	grub_message=$"Copy files: Скопируйте пакеты grub в /target и установите загрузчи"
elif [[ -n "$grub_dev" ]] ; then
	grub_button=$"--button=Install bootloader:3"    # Do not translate "button".
	grub_message=$"Установите загрузчик и завершите установку"
else
	grub_button=""
fi

if [[ -n "$esp_dev" ]] ; then
	chroot_message=$"$esp_dev уже должен быть установлен на /target/boot/efi/ (Проверьте ниже)"
fi

gpt_list=$(env LC_ALL=C fdisk -l | awk '/Disklabel type/ { print $3 }' | grep gpt)
bios_grub_dev=$(env LC_ALL=C fdisk -l | awk '/BIOS boot/ { print $1 }')
if [ "$uefi_boot" != yes ] ; then
	if [ -n "$gpt_list" ] && [ -z "$bios_grub_dev" ] ; then
		bios_boot_warning=$"\nПРЕДУПРЕЖДЕНИЕ: Загрузка с диска gpt не удастся без загрузки BIOS.\n"
	fi
fi

# Pause to allow manual changes to /target for UEFI boot.
df -h | yad --text-info --title=$"Установить загрузчик" --center --borders=10 --width=650 --height=600 \
	--text=$"${bios_boot_warning}
${grub_message}

Chroot: откроет терминал в корневой установке для пользовательской работы и
установки загрузчика вручную. 
${chroot_message}

Продолжить: будет продолжаться независимо от того, установлен ли у вас загрузчик. Если нет, то вам нужно будет иметь другой способ загрузить эту установку.

Abort: выйти из установщика и прервать установку

" \
"${grub_button}" --button=$"Abort":2 --button=$"Chroot":1 --button=$"Продолжить":0 
answer="$?"

if [[ $answer = 1 ]] ; then
	chroot_terminal
fi

if [[ $answer = 2 ]] ; then
	cleanup
	exit 0
fi

if [[ $answer = 3 ]] ; then
	install_grub
fi

if [[ $answer = 4 ]] ; then
#	grub_packages=$(yad --file --multiple --title=$"GRUB Packages" \
#		--text=$"Select the grub-efi-amd64 packages.\n\nBoth grub-efi packages will be copied to /target." \
#		--height=400 --width=500 --separator ' ')
#	cp  $(echo "$grub_packages") /target
	copy_grub_packages
fi




#******************************************************************

# Run update-initramfs to include dm-mod if using encryption
if [[ $encrypt_os = yes ]] || [[ $encrypt_home = yes ]] ; then
	if [[ -f /usr/sbin/update-initramfs.orig.initramfs-tools ]] ; then
		chroot /target /usr/sbin/update-initramfs.orig.initramfs-tools -u -k all >> "$error_log"
	else
		chroot /target /usr/sbin/update-initramfs -u -k all >> "$error_log"
	fi
fi


#******************************************************************



### This should not run if grub_dev=efi and Continue above (no bootloader)
#if [[ -n $grub_dev ]] || [[ -n $grub_partition ]] ; then
#    chroot /target update-grub ; check_exit 
#fi

if [ -f /target/boot/grub/setup_left_core_image_in_filesystem ]; then
	rm -f /target/boot/grub/setup_left_core_image_in_filesystem
fi

# INSTALLATION FINISHED - BEGIN CONFIGURE USERNAME, HOSTNAME, PASSWORDS, SUDO


# Need to mount the target home partition under the target root partition
# so the commands can find it (for changing user configs gksu)
if [[ $sep_home = "yes" ]]; then
    mount $home_part /target/home
fi


# it might not be on in some live builds
chroot /target /bin/bash -c "shadowconfig on"

oldname=$(awk -F: '/1000:1000/ { print $1 }' /target/etc/passwd)
old_realname=$(cat /target/etc/passwd |grep "^$oldname"|sed "s/,,,//"|awk -F ":" '{print $5}')

username_dialog() {

	newuser=$(yad --form --title=$"Настройте имя хоста и имени пользователя..." --center --borders=10 --button=$"OK":0 \
	--text=$"\n Вы должны изменить имя хоста и имя пользователя \n \
	(необязательно, но рекомендуется) \n" \
	--field=$"Новое имя хоста\ (без пробелов\):" \
	--field=$"Новое имя пользователя\ (без пробелов\):" \
	--field=$"«Настоящее имя» нового пользователя\ (например, Джон Смит\):" \
	--field=$"Разрешить sudo для нового пользователя\? (и сохранить учетную запись root)":CHK \
	--field=$"Используйте sudo по умолчанию для нового пользователя \? (и отключить учетную запись root)":CHK \
	--field=$"Используйте sudo только для выключения \? (и сохранить учетную запись root)":CHK \
	"$HOSTNAME" "$oldname" "$old_realname" FALSE FALSE FALSE)

	new_hostname=$(echo $newuser |awk -F "|" '{print $1}')
	newname=$(echo $newuser |awk -F "|" '{print $2}')
	new_realname=$(echo $newuser |awk -F "|" '{print $3}')
	sudoconfig=$(echo $newuser |awk -F "|" '{print $4}')
	sudo_is_default=$(echo $newuser |awk -F "|" '{print $5}')
	sudo_shutdown=$(echo $newuser |awk -F "|" '{print $6}')
}

username_dialog



# Test to make sure new_hostname is a legal hostname, let user fix it if it's not.
fix_hostname () {
	new_hostname=$(yad --entry --title=$"Изменить имя хоста" --center --borders=10 \
	--text=$"Неверное имя хоста. Попробуйте снова.
	
Вы можете использовать буквенно-цифровые символы в любом месте имени хоста, и
Вы можете использовать знак минус (-), если он не в начале или в конце." \
	--entry-text=$"$HOSTNAME" --width=500 --button=$"OK":0)
	test_hostname	
}


test_hostname () {
  if [[ -z $new_hostname ]]; then
    new_hostname="$HOSTNAME"
  fi
	if [[ ! "$new_hostname" =~ (^[a-zA-Z0-9]([a-zA-Z0-9]|-)+[a-zA-Z0-9]$) ]]; then
		fix_hostname
	fi
  hostname_len=${#new_hostname}
  if [[ $hostname_len -gt 63 ]]; then
    fix_hostname
  fi
}


# do hostname
if [[ $new_hostname != $HOSTNAME ]]; then
	test_hostname
	sed -i "s/$HOSTNAME/$new_hostname/" /target/etc/hostname
	sed -i "s/$HOSTNAME/$new_hostname/g" /target/etc/hosts
fi

# do username
if [ -z "$newname" ]; then
	newname=$oldname
fi

if [ "$oldname" != "$newname" ]; then

	chroot /target usermod -l $newname $oldname ; check_exit
	chroot /target groupmod -n $newname $oldname ; check_exit
	chroot /target usermod -d /home/$newname -m $newname ; check_exit

	for i in $(grep -r "/home/$oldname" /target/home/$newname/.config | awk -F":" '{ print $1 }'); do
	sed -i "s/\/home\/$oldname/\/home\/$newname/g" "$i"
	done

	for i in $(grep -r "/home/$oldname" /target/home/$newname/.local | awk -F":" '{ print $1 }'); do
	sed -i "s/\/home\/$oldname/\/home\/$newname/g" "$i"
	done
fi

chroot /target /bin/bash -c "chfn -f '$new_realname' $newname"


## sort sudo ##

# =>wheezy live-config now uses /etc/sudoers.d
if [ -e /target/etc/sudoers.d/live ]; then
rm -f /target/etc/sudoers.d/live
fi

oldusername=$(awk -F: '/1000:1000/ { print $1 }' /etc/passwd)
newusername=$(awk -F: '/1000:1000/ { print $1 }' /target/etc/passwd)

# squeeze (or other distro) might have used /etc/sudoers
if grep -qs $oldusername /target/etc/sudoers ; then
sed -i "/$oldusername/d" /target/etc/sudoers
fi

if [ "$sudoconfig" = "TRUE" ] || [ "$sudo_is_default" = "TRUE" ]; then
	# $newusername is permitted to use sudo so add him to sudo group
	chroot /target usermod -a -G sudo $newusername

		# it shoud be already there in =>wheezy.. in case it's not: 
		if ! grep -qs "^%sudo" /target/etc/sudoers ; then 
			echo "%sudo ALL=(ALL:ALL) ALL" >> /etc/sudoers
		fi
fi

if [ "$sudo_is_default" = "TRUE" ]; then
	# disable root account
	echo $"disabling root account.. "
	chroot /target passwd -d root
else
	# files that may have been written by live-config to force live sudo mode

	# should they just be deleted?

	# rm -f /target/home/*/.gconf/apps/gksu/%gconf.xml
	# rm -f /target/home/*/.*/share/config/*desurc

	# fix gksu in user's home ($newusername will not use sudo by default)
	if [ -f /target/home/"$newusername"/.gconf/apps/gksu/%gconf.xml ]; then
		sed -i '/sudo-mode/s/true/false/' /target/home/"$newusername"/.gconf/apps/gksu/%gconf.xml
	fi

	sed -i 's/SU_TO_ROOT_SU=sudo/SU_TO_ROOT_SU=su/' /target/home/$newusername/.su-to-rootrc
	# detects .kde/ .kde4/ .trinity/ (kdesurc or tdesurc)
	for file in /target/home/$newusername/.*/share/config/*desurc ; do
		sed -i 's/super-user-command=sudo/super-user-command=su/' $file
	done
fi

if [ "$sudo_shutdown" = "TRUE" ]; then
	sudo_include_file="/target/etc/sudoers.d/user_shutdown"
	if [ -f "$sudo_include_file" ]; then
		mv "$sudo_include_file" "${sudo_include_file}.old"
	fi
	# Make sure user gets removed from sudo group. In 2021/2022 sudo group is carried into installed system. Not sure why.
	chroot /target deluser "$newusername" sudo
	echo "$newusername ALL= NOPASSWD: /usr/sbin/pm-suspend, /usr/sbin/pm-hibernate, /sbin/halt, /sbin/reboot" > "$sudo_include_file"
fi


if [[ $disable_auto_desktop = "yes" ]]; then
	set_noautologin_desktop
	disable_auto_console="yes"
else
	set_autologin_desktop
fi   
    

# Disable console autologin
if [[ $disable_auto_console = "yes" ]]; then
	if grep -q "respawn:/bin/login -f" /target/etc/inittab ; then
		mv /target/etc/inittab /target/etc/inittab.$(date +%Y%m%d_%H%M)
		cp /usr/lib/refractainstaller/inittab.debian /target/etc/inittab
	fi
	if grep -q "$oldusername" /target/etc/sv/getty-tty*/run ; then
		sed -i 's/^\(.*\)getty\(.*\)-a\(.*\)'$oldusername'\(.*\)38400/\1getty 38400/' /target/etc/sv/getty-tty*/run
	fi
else
	sed -i "/respawn:/s/$oldusername/$newusername/g" /target/etc/inittab
	if [ -e /target/etc/sv/getty-tty*/run ] ; then
		sed -i "/38400/s/$oldusername/$newusername/" /target/etc/sv/getty-tty*/run
	fi
fi


# Remove diversion of anacron
if [ -e /usr/sbin/anacron.orig.anacron ] ; then
	dpkg-divert --no-rename --remove /usr/sbin/anacron
	mv /usr/sbin/anacron.orig.anacron /usr/sbin/anacron
fi


# live-config also writes directory /home/user/.kde
# if kde is not installed it should be removed !


## passwords ##

clean_log() {
	
	# clear the log of plain-text passwords
	if [ -n "$newpass" ]; then
		sed -i "s|$newpass|\*\*\*\*|"g $error_log
	fi
	
	if [ -n "$confirm_newpass" ]; then
		sed -i "s|$confirm_newpass|\*\*\*\*|"g $error_log
	fi
	newpass=""
	confirm_newpass=""
}

pass_error() {
	
	clean_log
	use_existing=""
	disable_root=""

	yad --title=$"Configure $pass_dialog password" --center --borders=10 --image="gtk-dialog-error" --width=320 --button=$"OK":0 \
	--text=$"  Пароли не совпадают (или флажок ошибка)  \n\n  Пожалуйста, попробуйте еще раз  "
}

configure_pass() {

	clean_log
	
	pass_entry=$(yad --form --title=$"Configure $pass_dialog password" --center --borders=10 --button=$"OK":0 \
	--text=$"Вы должны сбросить $pass_dialog пароль.\nUse TAB поменять поля." \
	--field=$"Введите новый $pass_dialog пароль::H" \
	--field=$"Подтвердите новый $pass_dialog пароль::H"  \
	--field=$"Использовать текущий пароль\? (не рекомендуется)":CHK)
	
	# TODO check for illegal characters?
	
	newpass=$(echo $pass_entry|awk -F "|" '{print $1}')
	confirm_newpass=$(echo $pass_entry|awk -F "|" '{print $2}')
	use_existing=$(echo $pass_entry|awk -F "|" '{print $3}')
	disable_root=$(echo $pass_entry|awk -F "|" '{print $4}')

	if [ "$use_existing" = "TRUE" ] && [ "$disable_root" = "TRUE" ] ; then
	pass_error
	configure_pass
	fi

	if [ -n "$newpass" ] && [ "$use_existing" = "TRUE" ]; then
	pass_error
	configure_pass
	fi

	if [ "$use_existing" = "TRUE" ] || [ "$disable_root" = "TRUE" ] ; then
	return
	fi

	if [ -z "$newpass" ] || [ "$newpass" != "$confirm_newpass" ]; then
	pass_error
	configure_pass
	fi
}

# do root password
set_rootpass() {

	pass_dialog=root
	configure_pass


	if [ -n "$newpass" ]; then
		chroot /target /bin/bash -c "echo -e \"$newpass\n$newpass\n\" | passwd root"
		#else do nothing, keep old password
	fi


	clean_log
}

# do user password
set_userpass() {

	pass_dialog=user
	configure_pass

	if [ -n "$newpass" ]; then
		chroot /target /bin/bash -c "echo -e \"$newpass\n$newpass\n\" | passwd $newusername"
		# else do nothing, keep old password
	fi

	clean_log
}

if [ "$sudo_is_default" != "TRUE" ]; then
	# Make sure user gets removed from sudo group. In 2021/2022 sudo group is carried into installed system. Not sure why.
	if [ "$sudoconfig" != "TRUE" ] ; then
		chroot /target deluser "$newusername" sudo
	fi
	set_rootpass
fi
set_userpass


# Run any post-install scripts
if [[ $run_postinstall = "yes" ]] ; then
	for file in /usr/lib/refractainstaller/post-install/* ; do
		if [[ -x "$file" ]] ; then
			bash "$file"
		fi
	done
fi


yad --image=gtk-dialog-info --title="$window_title" --center --borders=10 --text=$" Установка завершена. \n\n Теперь вы можете перезагрузиться в новую систему.\n\n Не забудьте удалить установочный носитель.\n" --width=500 --button=$"OK":0

# copy error log to installation now before calling cleanup function
cp "$error_log" /target/home/"$newusername"/
chown 1000:1000 /target/home/"$newusername"/"${error_log##*/}"
cleanup

exit 0
