#!/bin/bash
## Note: Some text editors in some lines its wrong the "markup color" because much '"'($) things.

## This function runs (non interactive) commands, and have various arguments, and logs it in $log file
## $1 -> Sentence to show
## $2 -> If it has to be silent (0->Show, 1/not 0->Silent)
## $3 -> Where to run (sudo: sudo $3, chroot: in the chroot as root, chuser: in chroot as the created user
## $4 -> Command to run
## $5 -> Is a "various-sentence command"? (0 -> First/Last/Unique, 1-> Not lastest )
function comm {
	local command
	local multic
	# Do not permit that $5 is empty. For multicommand/multisentence checks
	if [[ -z "$5" ]];then
		multic="0"
	else
		multic=$5
	fi
	
	# First complete the command, if necessary
	if [[ $3 == "chroot" ]];then
		command="chroot /mnt /bin/bash -c \"$4\""
	elif [[ $3 == "chuser" ]];then
		command="chroot /mnt /bin/bash -c \"su $nameuser -c \"$4\" \" "
	else
		command=$4
	fi

	
	# Check for multisentence command and run
	if [[ $multic == "0" ]];then
			echo "[ RUNNING ] $1"
	fi
	#Run command and make silent if its needed.
	if [[ $2 != "0" ]];then
		bash -c "$command" >/dev/null 1>/dev/null
		read
	else
		bash -c "$command"
	fi
	
	# When command finish, know if it ran succesfully
	if [[ $? != "0" ]];then
	echo "[ ERROR ] $1"
	echo "[ ERROR ] $1" >> /tmp/install.log
	fi
	
	if [ $? == "0" ] && [ $multic != "1" ];then
		echo "[ OK ] $1"
		echo "[ OK ] $1" >> /tmp/install.log
	fi

}


if [[ ! -f "jkarch" ]];then
	#Prepare system before install
	dialog --title "JKArch install script" --msgbox "Starting installation, please wait" 15 60
	# First add exec permisson to me
	chmod +x installer.sh
	# Grow cowspace
	comm "Grow cowspace for installer" "1" "sudo" "mount -o remount,size=700M /run/archiso/cowspace"

	#Enable pacman
	comm "Configuring pacman" "1" "sudo" "pacman-key --init" "0"
	comm "Configuring pacman" "1" "sudo" "pacman-key --populate" "0"
	comm "Configuring pacman" "1" "sudo" "pacman -Sy archlinux-keyring --noconfirm" "1"

	comm "Selecting mirrors" "1" "sudo" "pacman -S reflector --noconfirm" "0"
	comm "Selecting mirrors" "1" "sudo" "reflector --verbose -l 6 --sort rate --save /etc/pacman.d/mirrorlist" "1"

	#Delete programs (For not updating it)
	sudo pacman -R clonezilla darkhttpd diffutils grml-zsh-config irssi linux-atm lvm2 man-db man-pages mc ndisc6 nmap smartmontools testdisk vi vim vim-runtime openconnect pcsclite python2 python reflector --noconfirm
	sudo rm -rf /var/cache/pacman/pkg/*
	#Needed progs (gparted)
	sudo pacman -S gparted xf86-video-vesa xorg-xinit lwm xorg-xrandr xterm --noconfirm
	sudo rm -rf /var/cache/pacman/pkg/*
	#Update progs
	sudo pacman -Su --noconfirm --ignore linux #Do not upgrade kernel automatically
	sudo rm -rf /var/cache/pacman/pkg/*
	sudo rm /etc/X11/xinit/xinitrc
	sudo touch /etc/X11/xinit/xinitrc
	sudo chmod 777 /etc/X11/xinit/xinitrc
	sudo echo "#Start gparted with startx command" > /etc/X11/xinit/xinitrc
	sudo echo "lwm &" >> /etc/X11/xinit/xinitrc
	sudo echo "xrandr -s 1024x768 -r 60" >> /etc/X11/xinit/xinitrc
	sudo echo "xterm -e '/root/installer.sh' -geometry 120x35" >> /etc/X11/xinit/xinitrc
	sudo chmod 644 /etc/X11/xinit/xinitrc
	sudo rm -rf /var/cache/pacman/pkg/*
	# System prepared, now start installer
	touch /root/jkarch
	startx
	#Exit this.
	exit
fi


#First of all, the language
idiom=`dialog --stdout --nocancel --backtitle "JKArch Instalation" --title "Language selection" --menu "Select your language / Selecciona tu idioma" 0 70 5 1 "Spanish (es)" 2 "English (en) (In progress)"`

if [[ $idiom -eq 1 ]];then
	sclang="es"
	loadkeys es
elif [[ $idiom -eq 2 ]];then
	sclang="en"
	loadkeys en
fi

#Now, translations
wget -nv https://gitlab.com/JKANetwork/JKArch/raw/master/installer/translations.sh -O translations.sh
source translations.sh

# No black screensaver
setterm -blank 0 -powerdown 0 -powersave off
# Fix for some chars
export NCURSES_NO_UTF8_ACS=1

# Functions

function pause {
	echo "$(T "Press enter to continue...")"
	read
}

function mostrardialog {
	local titled
	local msgd
	titled=$1
	msgd=$2
	dialog --title "$titled" --msgbox "$msgd" 15 60
}

function yesnobox {
	local title=$1
	#Return Y or N
	echo `dialog --stdout --nocancel --menu "$title" 0 0 4 Y "$(T "Yes")" N "No"`
}

function fatalerror {
	razon=$1
	mostrardialog "Error" "$(T "An error has ocurred, setup will be stopped") $razon"
	mostrardialog "Log" "$(T "You have a install log in") /tmp/install.log"
	exit
}

function isanetworkerror {
	if [[ $? != 0 ]];then
	fatalerror "$(T "Network connection error, please check it")"
	fi
}

function pacmanerror {
	if [[ $? != 0 ]];then
	fatalerror "$(T "Pacman error, problems in repositories, apologizes. You have to try later...")"
	fi
}

##This function logs and execute commands 
function execl { 
	local command
	echo "------" >> "/tmp/install.log"
	if [[ $1 != "chroot" && $1 != "chuser" ]];then #If it runs normally
	command="$1"
	for (( i=2; i<=$#; i++ ))
	do
		command="$command $(echo $* | cut -f$i -d" ")"
	done
	echo "$command" >> "/tmp/install.log"
	$command
	else #There is a "First word", avoid it
	for (( i=2; i<=$#; i++ ))
	do
		command="$command $(echo $* | cut -f$i -d" ")"
	done
	fi

	if [[ $1 = "chroot" ]];then #If it runs in chroot
	echo "(In the install partition/chroot) $command" >> "/tmp/install.log"
	chroot /mnt /bin/bash -c "$command"
	elif [[ $1 = "chuser" ]];then #If it has to run in chroot but in the user name
	echo "(In a 'user' chroot in install partition) $command" >> "/tmp/install.log"
	chroot /mnt /bin/bash -c "su $nameuser -c \"$command\" "
	fi

	#Log result of the command
	if [[ $? == 0 ]];then
	echo "Result Ok " >> "/tmp/install.log"
	else
	echo "Error: Code $?" >> "/tmp/install.log"
	fi
}

##Function for show to the user if an option is on or off
function optstate {
	if [[ $1 =~ "$2" ]];then 
		echo "on"
	else 
		echo "off"
	fi
}


##Function to select by the user the partitions for the system install
function particiones {
	clear
	mostrardialog "$(T "Questions about partitions where system will be installed")" "$(T "Questions about partitions dialog. Text")"
	clear
	if [[ ! $(lsblk --output KNAME | cut -c1-3 | sort | uniq | sed '1d' | grep 'sd\|hd') ]];then
		mostrardialog "ERROR" "$(T "ERROR: You dont have HDD, insert one, poweroff")"
		reboot
	fi
	optpa=`dialog --stdout --nocancel --menu "$(T "¿Do you want to edit partitions?¿How?")" 0 0 5 1 "Grafico con Gparted (Recomendado)" 2 "Terminal (Pequeño asistente o por tu cuenta)" 3 "Borrar un disco duro e instalar JKArch en el (usar con cuidado!)" 4 "No editar nada"`
	case $optpa in
		1) 
			#Abrir gparted grafico
			mostrardialog "Gparted" "$(T "Gparted will be opened. Help text")"
			gparted;;
		2)
			#Terminal
			echo $(T "Select hard disk to edit")
			echo "Aviso, el soporte a GPT no es del 100%, si no vas a instalar mas SO y tu HDD no tiene mas de 2Tb, elija MBR/DOS"
			lsblk --output NAME,KNAME,FSTYPE,SIZE,LABEL
			options=($(lsblk --output KNAME | cut -c1-3 | sort | uniq | sed '1d' | grep 'sd\|hd') "No editar" "Terminal")
			select opt in "${options[@]}"
			do
				case $opt in
				"Terminal") 
				echo "Haga los cambios pertinentes, asegurese, y escriba exit continuar la instalación"
				bash
				break;;
				"No editar") break;;
				*) cfdisk /dev/$opt;break;;
				esac
			done
			;;
		3)
			mostrardialog "$(T "Full hard disk install")" "$(T "Full hard disk install. Text")"
			clear
			tput setaf 6 ; echo "$(T "Your partition scheme")" ; tput setaf 9
			lsblk --output NAME,KNAME,FSTYPE,SIZE,LABEL
			tput setaf 6 ; echo "$(T "Select hard disk to delete and use by JKArch")" ; tput setaf 9
			options=($(lsblk --output KNAME | cut -c1-3 | sort | uniq | sed '1d' | grep 'sd\|hd') "$(T "Exit")")
			select opt in "${options[@]}"
			do
				case $opt in
				"$(T "Exit")")
					mostrardialog "Instalacion detenida" "Se detuvo la instalacion. No se hicieron cambios. Al aceptar, reiniciara la instalacion"
					exec ./selectlang.sh
					;;
				*) 
					if [[ -z $opt ]];then
						echo "$(T "Not valid")"
					else
						optseg=`dialog --stdout --nocancel --menu "¿Estas seguro de borrar todo /dev/$opt y meter JKArch aqui? No es reversible" 0 0 4 1 "No" 2 "No" 3 "Si, estoy seguro" 4 "No"`
						case $optseg in
							3)
								echo -e "o\nn\np\n1\n\n\nw\n"  | fdisk /dev/$opt
								particionraiz=${opt}1
								hd="sda"  #This is for GRUB install
								formatoraiz="mkfs.ext4 -F"
								ram=$(free -m | grep Mem: | awk '1 {print $2 }')
								if [[ $ram -le 7500 ]];then
									swaptype=1
									swapamount=$(expr $ram / 3)
									if [[ $ram -le 3700 ]];then
										swapamount=$(expr $swapamount \* 2)
									fi
									if [[ $ram -le 1500 ]];then
										swapamount=$(expr $swapamount \* 2)
									fi
									if [[ $ram -le 700 ]];then
										swapamount=$(expr $swapamount \* 2)
									fi
								fi
								break;;
							*)
								mostrardialog "Instalacion detenida" "Se detuvo la instalacion. No se hicieron cambios. Al aceptar, reiniciara la instalacion"
								exec ./selectlang.sh
								;;
						esac
					fi;;
				esac
			done
			;;
	esac
	clear
	# Solo pedir datos si no esta en modo automatico, evidentemente.
	if [[ ! $optpa -eq 3 ]];then

		tput setaf 6 ; echo "$(T "Your partition scheme")" ; tput setaf 9
		lsblk --output NAME,KNAME,FSTYPE,SIZE,LABEL
		tput setaf 6 ; echo "$(T "I recommend to take notes before continue. Next, you will have the questions about it")" ; tput setaf 9
		pause
		
		harddisks=$(lsblk --output KNAME | cut -c1-3 | sort | uniq | sed '1d' | grep 'sd\|hd')
		i=3
		for addr in $(echo $harddisks | tr " " "\n")
		do
			varx+=" $addr '- $(lsblk --output SIZE /dev/$addr | sed '1d' | head -1)'"
		done
		varf="dialog --stdout --nocancel --menu \"Selecciona disco duro a utilizar para seleccionar las particiones\" 0 0 5 $varx"
		hd=`bash -c "$varf"`
		
		# Detectar tipo de tabla de particiones (gpt o msdos) y si es gpt, preparar para UEFI
		tabletype="$(parted /dev/${hd} p | grep "Partition Table" | awk '1 {print $3}')"

		if [[ $tabletype = "gpt" ]];then
			mostrardialog "$(T "GPT Partition Table")" "$(T "You are using GPT, you will have to select EFI")"
		fi
		clear
		
		variable=$(lsblk --output KNAME /dev/${hd} | cut -c1-4 | tail -n +3)
		i=3
		varx=""
		for addr in $(echo $variable | tr " " "\n")
		do
			varx+=" $addr '$(lsblk --output KNAME,FSTYPE,SIZE,LABEL /dev/${hd} | tail -n +$i | head -1)'"
			i=$((i+1))
		done
		varf="dialog --stdout --nocancel --menu \"Selecciona la particion raiz(/)\" 0 0 5 $varx"
		particionraiz=`bash -c "$varf"`
		
		optfr=`dialog --stdout --nocancel --menu "Formato para la particion raiz(/)" 0 0 4 1 "EXT4 (Recomendado)" 2 "BTRFS" 3 "XFS" 4 "No formatear (Si ya esta formateada)"`
		case $optfr in
			1) formatoraiz="mkfs.ext4 -F";;
			2) formatoraiz="mkfs.btrfs -f";;
			3) formatoraiz="mkfs.xfs -f";;		
			4) formatoraiz="echo No formatear ";;
		esac

		clear

		opthpart=`dialog --stdout --nocancel --menu "¿Quieres separar la particion /home de /?" 0 0 4 1 "No (Por defecto)" 2 "Si (Tendras que elegir la particion)"`
		case $opthpart in
			2)
				# Selección de home
				variable=$(lsblk --output KNAME /dev/${hd} | cut -c1-4 | tail -n +3)
				i=3
				varx=""
				for addr in $(echo $variable | tr " " "\n")
				do
					varx+=" $addr '$(lsblk --output KNAME,FSTYPE,SIZE,LABEL /dev/${hd} | tail -n +$i | head -1)'"
					i=$((i+1))
				done
				varf="dialog --stdout --nocancel --menu \"Selecctiona la particion home (/home)\" 0 0 5 $varx"
				particionhome=`bash -c "$varf"`
				
				if [[ $particionhome ]];then
					optfh=`dialog --stdout --nocancel --menu "Formato para la particion home (/home)" 0 0 4 1 "EXT4 (Recomendado)" 2 "BTRFS" 3 "XFS" 4 "No formatear (Si ya esta formateada)"`
					case $optfh in
						1) formatohome="mkfs.ext4 -F";;
						2) formatohome="mkfs.btrfs -f";;
						3) formatohome="mkfs.xfs -f";;
						4) formatohome="echo No formatear ";;
					esac
				fi
				;;
		esac
		
		if [[ $formatoraiz -eq "mkfs.btrfs -f" ]];then
			mostrardialog "No swapfile" "Es contraproducente hacer un fichero swap en una particion btrfs, no debes hacerlo, pero si antes creaste una particion swap, se puede utilizar"
		fi
		ram=$(free -m | grep Mem: | awk '1 {print $2 }')
		optswap=`dialog --stdout --nocancel --menu "¿Quieres crear un archivo swap (Memoria virtual)?" 0 0 4 1 "Si (Con valores por defecto, recomendado)" 2 "Si (Valores a mano)" 3 "Si, pero con una particion que ya cree" 4 "No"`
		case $optswap in
			1)
				# This count the ammount of swap to create dependent of computer RAM
				if [[ $ram -le 7500 ]];then
					swaptype=1
					swapamount=$(expr $ram / 3)
					if [[ $ram -le 3700 ]];then
						swapamount=$(expr $swapamount \* 2)
					fi
					if [[ $ram -le 1500 ]];then
						swapamount=$(expr $swapamount \* 2)
					fi
					if [[ $ram -le 700 ]];then
						swapamount=$(expr $swapamount \* 2)
					fi
				else
					# No es que sea necesario, pero como ha pulsado en si, se crea un archivo minimo"
					swaptype=1
					swapamount="512"
				fi
				;;
			2)	swapamount=`dialog --stdout --inputbox  "RAM: $(echo $ram) . $(T "Enter how much memory you want to use for swap (MB)")" 9 50`;;
			3)	mostrardialog "Swap" "$(T "JKArch autodetects swap partitions")";;
		esac

		clear

		if [[ $tabletype = "gpt" ]];then
		
			# Seleccion de particion EFI
			variable=$(lsblk --output KNAME /dev/${hd} | cut -c1-4 | tail -n +3)
			i=3
			varx=""
			for addr in $(echo $variable | tr " " "\n")
			do
				varx+=" $addr '$(lsblk --output KNAME,FSTYPE,SIZE,LABEL /dev/${hd} | tail -n +$i | head -1)'"
				i=$((i+1))
			done
			varf="dialog --stdout --nocancel --menu \"$(T 'Select EFI partition')\" 0 0 5 $varx"
			partefi=`bash -c "$varf"`
		fi

	fi
}

## Date and language
function horaidioma {
	while [[ $confirm != "Y" ]];do
		varx="" #Empty var
		langs=$(cat /etc/locale.gen | grep '^#[a-zA-Z]' | cut -f1 -d" " | cut -c2-30 | sort | uniq)
		for addr in $(echo $langs | tr " " "\n")
		do
			varx+=" $addr $addr"
		done
		varf="dialog --stdout --nocancel --menu \"$(T "Select language for JKArch")\" 0 0 5 $varx"
		opclang=`bash -c "$varf"`
		varx="" #Empty varx
		langabr=$(echo $opclang | cut -f1 -d"_")

		langinst=$(cat /etc/locale.gen | grep -m1 '^#'$opclang | cut -c2-40)
		
		#Confirm
		confirm=`yesnobox "$(T "Your language:") $opclang. Correcto?"`
	done #End of selecting lang
	confirm="" #Erase var
	
	echo "$(T "Now select your timezone for adjusting the clock")"
	while [[ $confirm != "Y" ]];do
	NEW_TIMEZONE=$(execl tzselect)
	confirm=`yesnobox "$(T "Your timezone is") $NEW_TIMEZONE ?"`
	done
	confirm="" #Erase var
}

##Function for make user select their user
function userpass {
	clear
	nameuser=`dialog --stdout --inputbox  "Nombre para tu usuario principal:" 10 50`
	until [[ $pass1 = $pass2 && $pass1 != "" ]]
	do
		pass1=`dialog --stdout --insecure --passwordbox  "$(T "Password for ") $nameuser" 9 50`
		pass2=`dialog --stdout --insecure --passwordbox  "$(T "Repeat password")" 9 50`
		if ! [[  $pass1 = $pass2 && $pass1 != "" ]];then
			mostrardialog "$(T "Password")" "$(T "Passwords do not match")"
		fi
	done
	passuser=${pass1}
	pass1="" #Reiniciar pass1, por si hace falta de nuevo que el until funcione


	#See if user wants to edit root password or not.
	opt=`dialog --stdout --nocancel --menu "$(T "You want to edit root (admin) password or set same as user?")" 0 0 4 1 "$(T "Same as user")" 2 "$(T "Edit")"`
	case $opt in
		1) passroot=${pass2};;
		2) until [[ $pass1 = $pass2 && $pass1 != "" ]]
			do
				pass1=`dialog --stdout --insecure --passwordbox  "$(T "Password for ") . root" 9 50`
				pass2=`dialog --stdout --insecure --passwordbox  "$(T "Repeat password")" 9 50`
				if ! [[  $pass1 = $pass2 && $pass1 != "" ]];then
					mostrardialog "$(T "Password")" "$(T "Passwords do not match")"
				fi
			done
			passroot=${pass2}
			pass1="" #Reiniciar pass1, por si hace falta de nuevo que el until funcione
			;;
	esac
}



##Interactive function for make user select some things (apps)
function appsuser {
	clear
		optbr=`dialog --stdout --nocancel --menu "¿Que navegador web utilizas?" 0 0 4 1 "Firefox" 2 "Chromium" 3 "Opera"`;
		case $optbr in
			1) packages="$packages firefox";;
			2) packages="$packages chromium";;
			3) packages="$packages opera";;
		esac

		confirm=`yesnobox "Habilitar soporte bluetooth?"`
		if [[ $confirm == "Y" ]];then
			packages="$packages bluez bluez-utils bluez-cups bluez-firmware bluez-libs blueberry "
		fi
		confirm=`yesnobox "Habilitar compatibilidad programas Windows (Usando wine)?"`
		if [[ $confirm == "Y" ]];then
			packages="$packages wine-staging wine_gecko winetricks"
			packages="$packages lib32-libpng lib32-libldap lib32-gnutls lib32-mpg123 lib32-libpulse lib32-ncurses lib32-openal lib32-alsa-lib lib32-gst-plugins-base-libs gnome-exe-thumbnailer samba" #Some 32bit libs for winearch 32 work better, and thumbs for .exe (samba needed too)
			inswine=1
		fi

		allpackages=$allpackages" "$packages
		packages=""
}


##Install and configure all of the system
function installconf {
	clear
	tput setaf 2 ; echo "$(T "Installing system, this can take about 20 minutes, wait")" ; tput setaf 9
	sleep 2
	tput setaf 2 ; echo "$(T "Formatting and mounting partitions")" ; tput setaf 9

	# Format and mount partitions
	execl $formatoraiz /dev/$particionraiz
	e2label /dev/$particionraiz "JKArch"
	execl mount /dev/$particionraiz /mnt/
	if [[ $particionhome ]];then
		execl $formatohome /dev/$particionhome
		mkdir -p /mnt/home/
		execl mount /dev/$particionhome /mnt/home/
	fi
	if [[ $partefi ]];then
		mkdir -p /mnt/boot/efi
		execl mount /dev/$partefi /mnt/boot/efi/
	fi

	# Download or install base system.
	execl wget -nv https://gitlab.com/JKANetwork/JKArch/raw/master/installer/pacman.conf -O pacman.conf
	#JKArch Mirrorlist needed
	execl wget -nv https://mirror.jkanetwork.com/Arch-repository/jkarch-mirrorlist -O /etc/pacman.d/jkarch-mirrorlist
	isanetworkerror # Comprueba si hubo un error de descarga
	tput setaf 2 ; echo "$(T "Downloading")" ; tput setaf 9
	#Install base and disk format drivers. Reflector and rsync is for updating mirrorlist later
	execl pacstrap -C pacman.conf /mnt/ base jkarch-mirrorlist reflector rsync dosfstools ntfs-3g btrfs-progs exfat-utils 
	pacmanerror
	# Copy pacman.conf
	execl cp pacman.conf /mnt/etc/pacman.conf
	
	# Create fstab
	execl genfstab -U /mnt > /mnt/etc/fstab
	# Create or activate swap if neccesary
	if [[ $swaptype ]];then
		case $swaptype in
			1)
				echo "$(T "Creating swap file")"
				dd if=/dev/zero of=/mnt/swapfile bs=1M count=$swapamount
				chmod 600 /mnt/swapfile
				mkswap /mnt/swapfile
				echo "/swapfile none swap defaults 0 0" >> /mnt/etc/fstab
				;;
		esac
	fi

	# Create bind mountpoints for the rest of the install (Chroot)
	
	cp -r /etc/netctl/* /mnt/etc/netctl/
	cp -f /etc/resolv.conf /mnt/etc/resolv.conf
	mount --bind /sys /mnt/sys
	mount --bind /proc /mnt/proc
	mount --bind /dev /mnt/dev
	mount --bind /run /mnt/run
	#

	# Var allpackages have in this moment all the packages selected by user, and will be the install packages list for pacman #
	# Do allpackages var contain base packages and NTP daemon (Hour sync)
	allpackages=$allpackages" jka-toolkit git wget netctl iw wpa_supplicant dialog sudo alsa-utils bash-completion ntp"

	#Mate desktop and apps
	allpackages=$allpackages" mate gtk-engine-murrine mate-media"
	allpackages=$allpackages" xorg-server xorg-xinit xorg-server-common xf86-input-libinput xterm lightdm lightdm-gtk-greeter gvfs gvfs-mtp gvfs-smb gvfs-afc udisks2 networkmanager network-manager-applet gnome-keyring xdialog lxterminal ttf-inconsolata octopi octopi-notifier gksu pulseaudio pavucontrol xdg-user-dirs jkarch-appearance xfce4-power-manager lxtask"

	# Standard packages
	allpackages="$allpackages flashplugin evince ristretto librsvg gnome-calculator gnome-disk-utility file-roller lrzip p7zip unace unrar tumbler poppler-glib ffmpegthumbnailer libgsf notepadqq leafpad libreoffice-fresh vlc qt4 noto-fonts noto-fonts-cjk noto-fonts-emoji ttf-dejavu ttf-liberation ttf-ms-fonts"
	
	# If spanish, add spanish lang
	if [[ $sclang == "es" ]];then
		allpackages="$allpackages libreoffice-fresh-es firefox-i18n-es-es"
	fi
	
	#Printers and scanners
	allpackages="$allpackages foomatic-db-engine foomatic-db foomatic-db-ppds hplip xsane cups cups-filters cups-pk-helper system-config-printer gtk3-print-backends"

	# Before install, configure mirrorlist
	execl chroot reflector --verbose -l 6 --sort rate --save /etc/pacman.d/mirrorlist
	# Here, allpackages have the user selected packages because selected before. Then, install it
	execl chroot pacman -Syu $allpackages --noconfirm --needed 

	# Language
	sed -i "s/\#$langinst/$langinst/g" /mnt/etc/locale.gen
	echo "LANG=$opclang" > /mnt/etc/locale.conf
	echo "LANGUAGE=$opclang" >> /mnt/etc/locale.conf
	echo "LC_COLLATE=$opclang" >> /mnt/etc/locale.conf
	echo "KEYMAP=$langabr" > /mnt/etc/vconsole.conf
	execl chroot locale-gen
	clear

	# Timezone
	test -n "$NEW_TIMEZONE" && cp -fp /mnt/usr/share/zoneinfo/"$NEW_TIMEZONE" /mnt/etc/localtime
	execl chroot hwclock --systohc --utc
	execl chroot systemctl enable ntpd

	# User and desktop skel
	wget -nv https://gitlab.com/JKANetwork/JKArch/raw/master/installer/skeluser.tar.xz -O- | tar xJf - -C /mnt/

	# Create user
	execl chroot useradd -m -G wheel -s /bin/bash $nameuser
	echo "${nameuser}:${passuser}" | execl chroot chpasswd

	# Root password
	echo "root:${passroot}" | execl chroot chpasswd
	# Fix for some strange login bugs
	execl chroot chmod 755 /
	execl chroot chmod 755 /bin

	# Add sudo support for wheel users like user added
	sed -i "s/\# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/g" /mnt/etc/sudoers

	# User directory (Photos, Desktop..) create
	execl chroot xdg-user-dirs-update
	# Turn on some services
	execl chroot systemctl enable lightdm
	execl chroot systemctl enable NetworkManager
	execl chroot systemctl enable dhcpcd
	
	# Enable cupsd service for printing
	if [[ $cups = "1" ]];then
		execl chroot systemctl enable org.cups.cupsd
	fi

	# Configure wine if neccesary
	if [[ $inswine = "1" ]];then
		echo "$(T "Configuring wine for better experience") (32 bit winearch)"
		execl chuser WINEARCH=win32 wineboot -u
	fi


	# Set X11 keyboard, and user GKSU
	keyboardlayout
	# Modify gksu for ask user password and not root one
	execl chuser gconftool-2  --set /apps/gksu/sudo-mode --type=bool true --owner=$(echo $nameuser)

	# Hostname
	echo "JKArch" > /mnt/etc/hostname

	# Linux kernel
	execl chroot mkinitcpio -p linux #Hacemos el mkinitcpio después de tener instalados los gráficos

	confirm=`yesnobox "¿Instalar gestor de arranque? (Pulsar SI a no ser que sepas lo que haces)"`
	if [[ $confirm == "Y" ]];then
		# Install and configure bootloader GRUB/rEFInd
		if [[ -z $partefi ]];then #If it dont have EFI
			execl chroot pacman -S grub os-prober --noconfirm
			#Arranque silencioso
			sed -i 's/\GRUB_CMDLINE_LINUX_DEFAULT="quiet"/GRUB_CMDLINE_LINUX_DEFAULT="quiet loglevel=3 vga=current"/g' /mnt/etc/default/grub
			echo "Instalando GRUB para BIOS/MBR"
			#Se usa la variable ${hd} que se escogió al principio
			execl chroot grub-install --target=i386-pc /dev/${hd}
			execl chroot grub-mkconfig -o /boot/grub/grub.cfg
		else #With EFI
			echo "Instalando rEFInd para UEFI"
			execl chroot pacman -S efibootmgr dosfstools refind-efi --noconfirm
			execl chroot refind-install
			rootuuid=$(blkid -o value -s UUID /dev/$(echo $particionraiz))
			echo '"Boot with standard options"        "root=UUID='$(echo $rootuuid)' rw add_efi_memmap quiet loglevel=3 vga=current"' > /mnt/boot/refind_linux.conf
			echo '"Boot in nomodeset mode"          "root=UUID='$(echo $rootuuid)' rw add_efi_memmap quiet loglevel=3 vga=current nomodeset"' >> /mnt/boot/refind_linux.conf
			echo '"Boot to single-user mode"          "root=UUID='$(echo $rootuuid)' rw add_efi_memmap quiet single"' >> /mnt/boot/refind_linux.conf
			echo '"Boot with minimal options"         "root=UUID='$(echo $rootuuid)' rw add_efi_memmap"' >> /mnt/boot/refind_linux.conf
		fi
	fi


	# Clean pacman
	echo "$(T "Cleaning")"
	execl chroot rm -rf $sfslocate/var/cache/pacman/pkg/*
	execl chroot pacman -Sc --noconfirm
} # Fin installconf


### More optional configs ###
function otrasconfig {
mostrardialog "$(T "Other configs")" "Aquí puedes seleccionar otras configuraciones que puedes hacer a Arch antes de terminar la instalacion, como su nombre"
# Loop infinito en otras configuraciones hasta que se pulse la de terminar
for (( ; ; ))
do
	othopt=`dialog --stdout --nocancel --menu "$(T "Other configs")" 0 0 8 e "Nada mas / Finalizar instalacion" 1 "Cambiar hostname (Nombre pc)" 2 "Usar otra distribucion de teclado como principal" 3 "Habilitar AUR (con yaourt)"`
	if [[ $othopt = "e" ]];then
		break
	else
		case $othopt in
			1)
				echo ""
				nam=`dialog --stdout --inputbox  "Nombre para el ordenador" 9 50`
				echo $nam > /mnt/etc/hostname
				;;
			2) 
				echo "Escoja su idioma para la distribucion del teclado"
				options=($(cat /mnt/etc/locale.gen | grep '^#[a-zA-Z]' | cut -c2-30 | cut -f1 -d"_" | sort | uniq))
				select opt in "${options[@]}"
				do
					case $opt in
						*) langabr=$opt;break;;
					esac
				done
				#Cambiar el layout del teclado por el nuevo
				keyboardlayout
				;;
			3) execl chroot pacman -S yaourt base-devel --noconfirm --needed;;
		esac
	fi
done
}

## Set X11 keyboard 
function keyboardlayout {
	echo "KEYMAP=$langabr" > /mnt/etc/vconsole.conf
	echo "# Read and parsed by systemd-localed. It's probably wise not to edit this file" > /mnt/etc/X11/xorg.conf.d/00-keyboard.conf
	echo "# manually too freely." >> /mnt/etc/X11/xorg.conf.d/00-keyboard.conf
	echo 'Section "InputClass"' >> /mnt/etc/X11/xorg.conf.d/00-keyboard.conf
	echo '    Identifier "system-keyboard"' >> /mnt/etc/X11/xorg.conf.d/00-keyboard.conf
	echo '    MatchIsKeyboard "on"' >> /mnt/etc/X11/xorg.conf.d/00-keyboard.conf
	echo '    Option "XkbLayout" "'$langabr'"' >> /mnt/etc/X11/xorg.conf.d/00-keyboard.conf
	echo 'EndSection' >> /mnt/etc/X11/xorg.conf.d/00-keyboard.conf
}

##End of declaring functions, start of script


#Start install
clear
mostrardialog "$(T "JKArch install script")" "$(T "Intro arch install script")"

mostrardialog "JKArch" "El script esta en estado beta y puede haber fallos. En caso de fallo, vuelva a probar en unas horas o con la versión offline.\nTambien podeis mandarnos un correo a contacto@jkanetwork.com y usar el log guardado en /tmp"

echo "Desmontando posibles particiones"
umount /mnt/boot/efi/
umount /mnt/*
umount /mnt/

# Start questions, functions for timezone, enviroment, programs...

particiones
horaidioma 

#Graficos (Falta la parte de VM)
allpackages=$allpackages" "$(pacman -Ssq xf86-video-*)

#Aqui va la personalizacion de programas, ya que son graficos.
appsuser

# Ask for user and password for the new system
userpass

clear
#                 Resumen de los cambios
tput setaf 6
echo "$(T "Ok, last thing before start installing, summary of changes")"
echo "$(T "Partition scheme before your changes")"
tput setaf 9
lsblk --output NAME,KNAME,FSTYPE,SIZE,LABEL
tput setaf 6
echo "$(T "Your changes")"
tput setaf 9
case $formatoraiz in
	"mkfs.ext4 -F")
		mosfraiz="$(T "ext4 formatted")";;
	"mkfs.btrfs -f")
		mosfraiz="$(T "btrfs formatted")";;
	"mkfs.xfs -f")
		mosfraiz="$(T "XFS formatted")";;
	"echo No formatear ")
		mosfraiz="$(T "not formatted")";;
esac
echo "$(T "Root partition"): $particionraiz , $mosfraiz"
if [[ $particionhome ]];then
case $formatohome in
	"mkfs.ext4 -F")
		mosfhome="$(T "ext4 formatted")";;
	"mkfs.btrfs -f")
		mosfhome="$(T "btrfs formatted")";;	
	"mkfs.xfs -f")
		mosfhome="$(T "XFS formatted")";;
	"echo No formatear ")
		mosfhome="$(T "not formatted")";;
esac
echo "$(T "Home partition"): $particionhome , $mosfhome"
fi
if [[ $partefi ]];then
	echo "$(T "EFI partition in") $partefi"
fi

#  Log options
echo "------" >> "/tmp/install.log"
echo "Install partition options" >> "/tmp/install.log"
if [[ $mosfraiz != "$(T "not formatted")" ]];then
	echo "Format $mosfraiz the partiton $particionraiz for root" >> "/tmp/install.log"
else
	echo "Root partition $particionraiz not formatted" >> "/tmp/install.log"
fi
if [[ $particionhome ]];then
	if [[ $mosfhome != "$(T "not formatted")" ]];then
	echo "Format $mosfhome the partiton $particionhome for /home" >> "/tmp/install.log"
	else
	echo "Home partition $particionhome not formatted" >> "/tmp/install.log"
	fi
fi
#


#Pregunta si instalar o no
tput setaf 1 
echo "¿Estas de acuerdo con los cambios y quieres comenzar la instalacion?"
options=("No, volver a empezar" "Si, instalar" "No, apagar el ordenador")
select opt in "${options[@]}"
do
	case $opt in
	"No, volver a empezar") 
	rm /tmp/install.log
	exec ./selectlang.sh
	break;;
	"Si, instalar") break;;
	"No, apagar el ordenador")
		poweroff
		exit
	;;
	esac
done
tput setaf 9

# Real install
pause

installconf

#End install, other user configs (If it wants it)
otrasconfig

echo "Sincronizando datos al disco duro, puede tardar unos segundos"
sync

clear
mostrardialog "$(T "End")" "$(T "Setup finished, press enter to reboot.")"
#Move log
mv /tmp/install.log /mnt/home/$nameuser/install.log

# Unmounting partitions
umount /mnt/*
umount /mnt
# Reboot, finished
reboot