#!/bin/sh
#
# Setting variables
title="Instalador ArchLinux v1.00"
#
msg() { 
#
if [ "$1" = "q" ]; then 
   zenity --question --height=500 --width=450 --title="$title" --text="$2"
   rtm=$?
fi
#
if [ "$1" = "i" ]; then 
   zenity --info --height=500 --width=450 --title="$title" --text="$2"
   rtm=$?
fi
#
if [ "$1" = "p" ]; then 
   zenity --progress --title="$title" --width=450 --pulsate --auto-close --no-cancel
fi
#
if [ "$1" = "l" ]; then 
   rtm="zenity --list --radiolist --height=500 --width=450 --text "
fi
#
if [ "$1" = "c" ]; then 
   rtm="zenity --list --radiolist --height=500 --width=450 --column Select --column "
fi
#
if [ "$1" = "a" ]; then 
   rtm="zenity --list --checklist --height=500 --width=450 --text "
fi
#
if [ "$1" = "e" ]; then 
   rtm="zenity --entry --text "
fi
#
}

#msg_l="zenity --list --radiolist --height=500 --width=450 --text "
#msg_c="zenity --list --radiolist --height=500 --width=450 --column Select --column "
#msg_e="zenity --entry --text "

# Greeting user and advising user to connect if not already
greeting() { 
msg q "Bem vindo ao Instalador ArchLinux v1.00.\n\nSe assegure que existe conexão com a internet.\n\nSe precisar conectar via 'WiFi', você pode clicar no ícone de Rede\nlogo abaixo perto do relogio e configurar a mesma.\n\nSe estiver usando a Rede cabeada ela será conectada 'Automaticamente'.\n\nQuando estiver conectado a Internet click no botão 'Sim' para continuar a instalação.\n\nSe você quiser sair do instalador click no botão 'Não'."
if [ "$rtm" = "1" ]
	then exit
fi
}
#
#Pulling dependencies
pulling() {
zenity --info --title="$title" --auto-close
#
if [ "$rtm" = "1" ]
	then exit
else (
# updating pacman cache
echo "# Atualizando Pacman Cache..."
echo "20"
pacman -Syy
echo "50"
pacman -S --noconfirm arch-install-scripts archiso pacman-contrib zenity gparted
echo "# Atualização Finalizada..."
) | zenity --progress  --percentage=0  --title="$title" --width=450 --no-cancel --auto-close
fi
}

# Selecting the Drive
man_partition() {
list=` lsblk -lno NAME,TYPE,SIZE,MOUNTPOINT | grep "disk" `

msg i "Abaixo esta exibida a lista de Discos(HD/SSD) no seu sistema:\n\n$list"

lsblk -lno NAME,TYPE | grep 'disk' | awk '{print "/dev/" $1 " " $2}' | sort -u > devices.txt
sed -i 's/\<disk\>//g' devices.txt
devices=` awk '{print "FALSE " $0}' devices.txt `
msg l
dev=$($rtm "Selecione o disco que voce quer usar para a instalação." --column Disco --column Informação $devices)

# Partitioning
# Allow user to partition using gparted
msg q "Voce quer particionar o disco '$dev'?\n\nSelecione 'Sim' para abrir o gparted e particionar o disco\nou formatar as partições se necessario.\n\nO instalador não formatara as partições depois,\nassim se as partições precisarem ser formatadas/nselecione 'Sim' e use o gparted para formata-las."
if [ "$rtm" = "0" ]
	then gparted
fi

	# Select root partition
	msg l
	root_part=$($rtm "Escolha a partição para ser usada como 'root' do sistema.\n\nAviso! Esta lista mostra todas as partições disponiveis no disco.\n\nAtenção! Escolha com cuidado a qual vai usar." --column 'Selecione' --column 'Partições' $(fdisk -l | grep dev | grep -v Disco | awk '{print $1}' | awk '{ printf " FALSE ""\0"$0"\0" }'))
	#mounting root partition
touch root_part.txt    
echo $root_part >> root_part.txt
	mount $root_part /mnt

	# Swap partition?
	msg q "Voce quer usar uma partição como 'swap'?"
		if [ "$rtm" = "0" ]
		then 
		msg l
		swap_part=$($rtm "Escolha partição para ser usada como 'swap'.\n\nAviso! Esta lista mostra todas as partições disponiveis no disco.\n\nAtenção! Escolha com cuidado a qual vai usar.." --column 'Selecione' --column 'Partições' $(fdisk -l | grep dev | grep -v Disco | awk '{print $1}' | awk '{ printf " FALSE ""\0"$0"\0" }'))
		mkswap $swap_part
		swapon $swap_part
		fi
	msg q "Voce gostaria de criar um arquivo de 1GB de 'swap'\nno sistema de arquivos?\n\nSe voce ja selecionou uma partição de 'swap' anteriormente\nou não quer criar a mesma selecione 'Não'.\n\nCaso contrario selecione 'Sim' para criar o arquivo de 'Swap'\nisso ira demorar algum tempo, por isso aguarde."
		if [ "$rtm" = "0" ]
	 	then swapfile="yes"
		(echo "# Criando o swapfile..."
		touch /mnt/swapfile
		dd if=/dev/zero of=/mnt/swapfile bs=1M count=1024
		chmod 600 /mnt/swapfile
		mkswap /mnt/swapfile
		swapon /mnt/swapfile) | msg p
		fi

	# Boot Partition?
	msg q "Voce quer usar uma partiçao separada para o 'boot'?" 
		if [ "$rtm" = "0" ]
		then 
		msg l
		boot_part=$($rtm "Selecione a partição para usar como '/boot'." --column 'Selecione' --column 'Partição' $(fdisk -l | grep dev | grep -v Disco | awk '{print $1}' | awk '{ printf " FALSE ""\0"$0"\0" }'))

		mkdir -p /mnt/boot
		mount $boot_part /mnt/boot

		fi

	# Home Partition?
	msg q "Voce quer usar uma partiçao separada para o 'home'?" 
		if [ "$rtm" = "0" ]
		then 
		msg l
		home_part=$($rtm "Selecione a partição para usar como '/home'." --column 'Selecione' --column 'Partição' $(fdisk -l | grep dev | grep -v Disco | awk '{print $1}' | awk '{ printf " FALSE ""\0"$0"\0" }'))
		# mounting home partition
		mkdir -p /mnt/home
		mount $home_part /mnt/home
		fi
}

auto_partition() {
	list=` lsblk -lno NAME,TYPE,SIZE,MOUNTPOINT | grep "disk" `

	msg i "Esta lista mostra todas os discos disponiveis no seu sistema:\n\n$list" 

	lsblk -lno NAME,TYPE | grep 'disk' | awk '{print "/dev/" $1 " " $2}' | sort -u > devices.txt
	sed -i 's/\<disk\>//g' devices.txt
	devices=` awk '{print "FALSE " $0}' devices.txt `
	msg l
	dev=$($rtm "Selecione o disco que voce quer usar para a instalação." --column Drive --column Info $devices)

	msg q "Aviso! Esta operãção ira apagar todos os dados no disco $dev\!\nVoce tem certeza que quer continuar? Selecione 'Sim' para continuar ou 'Não' para voltar."
        yn="$rtm"
        touch root_part.txt
        if [ "$SYSTEM" = "BIOS" ]
	then echo {$dev}1 >> root_part.txt
	else echo {$dev}2 >> root_part.txt
        fi 
	if [ "$yn" = "1" ]
	then partition
	fi

	# Find total amount of RAM
	ram=$(grep MemTotal /proc/meminfo | awk '{print $2/1024}' | sed 's/\..*//')
	# Find where swap partition stops
	num=4000

	if [ "$ram" -gt "$num" ]
		then swap_space=4096
		else swap_space=$ram
	fi
	
	uefi_swap=$(($swap_space + 513))


	#BIOS or UEFI
    if [ "$SYSTEM" = "BIOS" ]
        then
	       (echo "# Criando as Partições para BIOS..."
	        dd if=/dev/zero of=$dev bs=512 count=1
	        Parted "mklabel msdos"
	        Parted "mkpart primary ext4 1MiB 100%"
	        Parted "set 1 boot on"
	        mkfs.ext4 -F ${dev}1
	        mount ${dev}1 /mnt
		touch /mnt/swapfile
		dd if=/dev/zero of=/mnt/swapfile bs=1M count=${swap_space}
		chmod 600 /mnt/swapfile
		mkswap /mnt/swapfile
		swapon /mnt/swapfile
		swapfile="yes") | msg p
	    else
            	(echo "# Criado as Partições para  UEFI..."
            	dd if=/dev/zero of=$dev bs=512 count=1
            	Parted "mklabel gpt"
            	Parted "mkpart primary fat32 1MiB 513MiB"
		Parted "mkpart primary ext4 513MiB 100%"
		Parted "set 1 boot on"
		mkfs.fat -F32 ${dev}1
		mkfs.ext4 -F ${dev}2
		mount ${dev}2 /mnt
		mkdir -p /mnt/boot
		mount ${dev}1 /mnt/boot
		touch /mnt/swapfile
		dd if=/dev/zero of=/mnt/swapfile bs=1M count=${swap_space}
		chmod 600 /mnt/swapfile
		mkswap /mnt/swapfile
		swapon /mnt/swapfile
		swapfile="yes") | msg p
	fi
			
}

partition() {
#
	msg l
	ans=$($rtm "Voce gostaria de usar o particionamento 'Automatico' do disco?\nOu particionar 'Manualmente' o disco para instalação?\nO particionamento 'Automatico' ira apagar totalmentedo o disco Selecionado." --column Selecione --column Escolha FALSE "Automatico" FALSE "Manualmente")
	if [ "$ans" = "Automatico" ]
	then auto_partition
	else
	man_partition
	fi
}

configure() {
# Getting Locale
msg c
country=$($rtm Country --text "Selecione o codigo do seu Pais.\nEsse sera usado como o Idioma do Sistema ex.: 'BR'." FALSE all FALSE AU FALSE AT FALSE BD FALSE BY FALSE BE FALSE BA FALSE BR FALSE BG FALSE CA FALSE CL FALSE CN FALSE CO FALSE HR FALSE CZ FALSE DE FALSE DK FALSE EE FALSE ES FALSE FR FALSE GB FALSE HU FALSE IE FALSE IL FALSE IN FALSE IT FALSE JP FALSE KR FALSE KZ FALSE LK FALSE LU FALSE LV FALSE MK FALSE NL FALSE NO FALSE NZ FALSE PT FALSE RO FALSE RS FALSE RU FALSE SU FALSE SG FALSE SK FALSE TR FALSE TW FALSE UA FALSE US FALSE UZ FALSE VN FALSE ZA)
locales=$(cat /etc/locale.gen | grep -v "#  " | sed 's/#//g' | sed 's/ UTF-8//g' | grep .UTF-8 | sort | awk '{ printf "FALSE ""\0"$0"\0" }')
msg l
locale=$($rtm "Selecione a sua Lingua / Idioma ex.: pt_BR.UTF-8." --column Selecione --column Local TRUE en_US.UTF-8 $locales)

msg q "Voce gostaria de trocar o modelo do seu teclado?\n\nO padrão é o pc105."
mod="$rtm"

if [ "$mod" = "0" ]
then 
msg l
model=$($rtm "Selecione o Modelo do seu Teclado." --column Selecione --column Modelo $(localectl list-x11-keymap-models | awk '{ printf " FALSE ""\0"$0"\0" }'))
fi
msg l
layout=$($rtm "Selecione o Layout do seu Teclado, codigo do seu pais ex.: 'br'." --column Selecione --column Layout $(localectl list-x11-keymap-layouts | awk '{ printf " FALSE ""\0"$0"\0" }'))

msg q "Voce gostaria de trocar a variante do seu Teclado?"
vary="$rtm"

if [ "$vary" = "0" ]
then 
msg l
variant=$($rtm "Selecione a variante preferida." --column Selecione --column Variante $(localectl list-x11-keymap-variants | awk '{ printf " FALSE ""\0"$0"\0" }'))
fi

msg q "Você encontrou seu mapa de Teclado em alguma das opções anteriores? ex.: 'br-abnt2'." 
map="$rtm"

if [ "$map" = "1" ]
then 
msg l
keymap=$($rtm "Selecione o seu teclado." --column Selecione --column Teclado $(localectl list-keymaps | awk '{ printf " FALSE ""\0"$0"\0" }'))
loadkeys $keymap
fi

setxkbmap $layout

if [ "$model" = "0" ] 
then setxkbmap -model $model 
fi

if [ "$vary" = "0" ] 
then setxkbmap -variant $variant
fi
# Getting Timezone
zones=$(cat /usr/share/zoneinfo/zone.tab | awk '{print $3}' | grep "/" | sed "s/\/.*//g" | sort -ud | sort | awk '{ printf " FALSE ""\0"$0"\0" }')
msg l
zone=$($rtm "Selecione o Fuso-Horario do seu país/zone." --column Selecione --column Fuso $zones)

subzones=$(cat /usr/share/zoneinfo/zone.tab | awk '{print $3}' | grep "$zone/" | sed "s/$zone\///g" | sort -ud | sort | awk '{ printf " FALSE ""\0"$0"\0" }')
msg l
subzone=$($rtm "Selecione o Fuso-Horario / sub-zone." --column Selecione --column Fuso $subzones)

# Getting Clock Preference
msg l
clock=$($rtm "Deseja usar o relogio em UTC ou hora local?\n\nO UTC é recomendado, a menos que você esteja inicializando boot duplo com o Windows." --column Selecione --column Horario TRUE utc FALSE localtime)

# Getting hostname, username, root password, and user password
msg e
hname=$($rtm "Insira um nome de 'host' para o seu sistema.\nDeve estar em letras minúsculas." --entry-text "archlinux")
msg e
username=$($rtm "Por favor,\nInsira um nome para o 'Novo' usuário do sistema.\nDe novo, em letras minúsculas." --entry-text "user")
}

vbox() {
graphics=$(lspci | grep -i "vga" | sed 's/.*://' | sed 's/(.*//' | sed 's/^[ \t]*//')
if [[ $(echo $graphics | grep -i 'VMware') != "" ]]
	then msg q "O instalador detectou que você está executando o Virtualbox.\n\nDeseja instalar o Virtualbox Utilities no sistema instalado? "
vb="$rtm"
fi
}

nvidia() {
graphics=$(lspci | grep -i "vga" | sed 's/.*://' | sed 's/(.*//' | sed 's/^[ \t]*//')
3D="(VGA|3D)"
card=$(lspci -k | grep -A 2 -E $3D)
if [[ $(echo $card | grep -i 'nvidia') != "" ]]
	then msg q "O Instalador detectou que você está executando uma placa de vídeo Nvidia. \ NGostaria de instalar drivers gráficos proprietários da Nvidia no sistema instalado? "
		if [ "$rtm" = "0" ]
			then 
			msg l
			video=$($rtm "You will need to know what model of NVIDIA graphics card you are using.\nFor NVIDIA 400 series and newer install nvidia and nvidia-libgl.\nFor 8000-9000 or 100-300 series install nvidia-304xx and nvidia-304xx-libgl.\n\nYour current graphics card is:\n$card\n\n
	 the NVIDIA drivers that you would like to install." --column "Selecione" --column "Driver" FALSE "nvidia nvidia-utils nvidia-settings" FALSE "nvidia-304xx nvidia-304xx-utils nvidia-settings" FALSE "nvidia-340xx nvidia-340xx-utils nvidia-settings" FALSE "nvidia-lts nvidia-settings nvidia-utils" FALSE "nvidia-340xx-lts nvidia-340xx-utils nvidia-settings" FALSE "nvidia-304xx-lts nvidia-304xx-utils nvidia-settings" FALSE "nvidia-dkms" FALSE "nvidia-340xx-dkms" FALSE "nvidia-304xx-dkms")
			else video="mesa xf86-video-nouveau"
		fi
	else video="mesa xf86-video-nouveau"
fi
}

kernel() {
msg l
kernel=$($rtm "Existem vários kernels disponíveis para o sistema.\n\nO mais comum é o kernel Linux atual.\nEste kernel é o mais atualizado, fornecendo o melhor suporte de hardware.\nNo entanto, pode haver possíveis bugs neste kernel, apesar de testado.\n\nO kernel linux-lts fornece um foco na estabilidade.\nEle é baseado em um kernel antigo, então pode faltar alguns recursos mais novos.\n\nO kernel linux-hardened é focado na segurança\nEle contém o Grsecurity Patchset e PaX para maior segurança.\n\nO kernel linux-zen é o resultado de uma colaboração de hackers do kernel \npara fornecer o melhor kernel possível para sistemas diários.\n\nPor favor, selecione o kernel que deseja instalar." --column "Selecione" --column "Kernel" FALSE linux FALSE linux-lts FALSE linux-hardened FALSE linux-zen)
}

root_password() {
msg e
rtpasswd=$($rtm "Por favor,\nDigite a senha para o 'root'." --hide-text)
msg e
rtpasswd2=$($rtm "Por favor,\nInsira novamente a senha para o 'root'. " --hide-text)
	if [ "$rtpasswd" != "$rtpasswd2" ]
		then zenity --error --height=500 --width=450 --title="$title" --text "As senhas não coincidem,\nTente novamente."
		root_password
	fi
}

changeshell() {
msg l
shell=$($rtm "Qual shell voce gostaria de usar?" --column Selecione --column Escolha FALSE bash FALSE zsh FALSE fish)
}

user_password() {
msg e
userpasswd=$($rtm "Por favor,\nDigite a senha para novo usuario '$username'." --hide-text)
msg e
userpasswd2=$($rtm "Por favor,\nInsira novamente a senha para o novo usuario '$username'." --hide-text)
	if [ "$userpasswd" != "$userpasswd2" ]
		then zenity --error --height=500 --width=450 --title="$title" --text "As senhas não coincidem,\nTente novamente."
		user_password
	fi
}

cups() {
msg q "Você gostaria de instalar o suporte para impressora? "
cp="$rtm"
}

desktop() {
# Choosing Desktop
msg l
desktops=$($rtm "Qual Desktop você gostaria de instalar?" --column Selecione --column Desktop FALSE "gnome" FALSE "gnome gnome-extra" FALSE "plasma" FALSE "plasma kde-applications" FALSE "xfce4" FALSE "xfce4 xfce4-goodies" FALSE "lxde" FALSE "lxqt" FALSE "mate" FALSE "mate mate-extra" FALSE "budgie-desktop" FALSE "budgie-desktop gnome" FALSE "cinnamon" FALSE "deepin" FALSE "deepin deepin-extra" FALSE "enlightenment" FALSE "jwm" FALSE "i3-wm i3lock i3status" FALSE "i3-gaps i3status i3lock" FALSE "openbox tint2" FALSE "Mais window managers")
if [ "$desktops" = "Mais window managers" ]
then 
msg l
$rtm "Olhe para esses gerenciadores de janela.\nVocê irá selecionar o que deseja na próxima etapa" --column View --width=450 --height=550 "$(pacman -Ss window manager)"
msg c
wm=$($rtm WM --title="$title" --radiolist --text "Qual Gerenciador de janelas você gostaria de usar?" $(pacman -Ssq window manager | awk '{ printf " FALSE ""\0"$0"\0" }'))
fi
}

displaymanager() {
msg l
dm=$($rtm "Qual gerenciador de exibição você gostaria de usar? " --column "Selecione" --column "Display Manager" FALSE "lxdm" FALSE "sddm" FALSE "gdm" FALSE "default")
}

#revengerepo() {
#msg q "Gostaria de adicionar 'chaoticrepo' ao seu /etc/pacman.conf?\n\nO 'chaoticrepo' contém alguns pacotes extras,\ncomo spotify e pamac."
#rr="$rtm"
#}

multilib() {
msg q "Você gostaria de habilitar repositórios 'multilib' em seu sistema?\n\nVocê pode precisar deles se usar Steam, Wine ou outro software de 32 bits? "
multilib="$rtm"
}

packagemanager() {
msg q "Você gostaria de instalar um gerenciador de pacotes gráfico?\n\nIsso permitirá que você instale e remova aplicativos sem lidar com a linha de comando " 
pm="$rtm"
if [ "$pm" = "0" ] 
then msg i "Escolha 'octopi' se estiver usando uma área de trabalho Qt como KDE ou LXQt.\n\nEscolha 'Pamac' se estiver usando um desktop GTK.\n\nSe você estiver usando apenas um gerenciador de janelas, você pode selecionar qualquer um deles sem quaisquer efeitos prejudiciais" 
msg l
pack=$($rtm "Qual gerenciador de pacotes você gostaria de instalar?" --column Selecione --column "Package Manager" FALSE octopi FALSE pamac-aur) 
fi
}

archuserrepo() {
msg q "Você gostaria de instalar o suporte para o repositório de usuários do Arch 'yay'? "
abs="$rtm"
}

# internet app list
internet_apps() {
msg a
$rtm "Selecione os aplicativos de Internet que deseja instalar " --column "Selecione" --column "Aplicativos" FALSE "chromium " FALSE "midori " FALSE "qupzilla " FALSE "netsurf " FALSE "filezilla " FALSE "opera " FALSE "evolution " FALSE "geary " FALSE "thunderbird " FALSE "transmission-gtk " FALSE "qbittorrent " FALSE "hexchat " > int2.txt
sed -i -e 's/[|]//g' int2.txt
}

# media app list
media_apps() {
msg a
$rtm "Selecione os aplicativos de mídia que deseja instalar" --column "Selecione" --column "Aplicativos" FALSE "kodi " FALSE "gimp " FALSE "vlc " FALSE "phonon-qt4-vlc " FALSE "totem " FALSE "parole " FALSE "audacious " FALSE "clementine " FALSE "gthumb " FALSE "shotwell " FALSE "ristretto " FALSE "gpicview " FALSE "brasero " FALSE "audacity " FALSE "simplescreenrecorder " FALSE "xfburn " FALSE "kdenlive " > med2.txt
sed -i -e 's/[|]//g' med2.txt
}

# office app list
office_apps() {
msg a
$rtm "Selecione os aplicativos de escritório que deseja instalar" --column "Selecione" --column "Aplicativos" FALSE "calligra " FALSE "abiword " FALSE "gnumeric " FALSE "pdfmod " FALSE "evince " FALSE "epdfview " FALSE "calibre " FALSE "fbreader " > off2.txt
sed -i -e 's/[|]//g' off2.txt
}

# utility app list
utility_apps() {
msg a
$rtm "Selecione os aplicativos utilitários que você gostaria de instalar" --column "Selecione" --column "Aplicativos" FALSE "htop " FALSE "neofetch " FALSE "gnome-disk-utility " FALSE "gparted " FALSE "partitionmanager " FALSE "synapse " FALSE "virtualbox " FALSE "gufw " FALSE "redshift " FALSE "leafpad " FALSE "geany " FALSE "parcellite " FALSE "grsync " FALSE "guake " FALSE "ntfs-3g " FALSE "btrfs-progs " FALSE "gptfdisk " FALSE "f2fs-tools " FALSE "exfat-utils "  FALSE "xfsprogs " FALSE "wireguard-tools " FALSE "wireguard-dkms " FALSE "openvpn " FALSE "network-manager-applet " > utils.txt
sed -i -e 's/[|]//g' utils.txt
}

customization_apps() {
msg a
$rtm "Selecione os aplicativos de personalização que deseja instalar" --column "Selecione" --column "Aplicativos" FALSE "breeze-gtk " FALSE "materia-gtk-theme " FALSE "deepin-gtk-theme " FALSE "arc-gtk-theme " FALSE "adapta-gtk-theme " FALSE "elementary-icon-theme " FALSE "arc-icon-theme " FALSE "papirus-icon-theme " FALSE "qt5ct "  > cust.txt
sed -i -e 's/[|]//g' cust.txt
}

# allowing user to select extra applications
update() {
	pacman -Syy
}

libreoffice() {
msg q "Você gostaria de instalar o 'libreoffice',\n\nUma alternativa de código-fonte aberto ao msoffice?"
lbr="$rtm"
if [ "$lbr" = "0" ]
then 
msg l
lover=$($rtm "'Libreoffice-fresh' é a versão mais recente do libreoffice,\n\nembora seja atualizado com menos frequência." --column Selecione --column Versão FALSE "fresh" FALSE "still")
msg c
lolang=$($rtm Langpack $(pacman -Ssq libreoffice-$lover lang | awk '{ printf " FALSE ""\0"$0"\0" }'))
fi
}

firefox() {
msg q "Gostaria de instalar o 'Firefox',\n\nUm navegador da fundação Mozilla? "
frf="$rtm"
if [ "$frf" = "0" ]
then 
msg c
fflang=$($rtm Langpack $(pacman -Ssq firefox lang  | awk '{ printf " FALSE ""\0"$0"\0" }'))
fi
}

installapps() {
msg l
extra=$($rtm "Se você quiser mais aplicativos para instalar,\n\nEscolha a categoria da lista abaixo.\n\nQuando terminar de selecionar os aplicativos\nem cada categoria, você retornará a este menu.\n\nEntão, basta selecionar 'Finalizei' quando terminar. " --column Selecioe --column Categoria FALSE internet FALSE media FALSE office FALSE utilities FALSE customization FALSE Finalizei)

if [ "$extra" = "internet" ]
	then internet_apps;installapps
elif [ "$extra" = "media" ]
	then media_apps;installapps
elif [ "$extra" = "office" ]
	then office_apps;installapps
elif [ "$extra" = "utilities" ]
	then utility_apps;installapps
elif [ "$extra" = "customization" ]
then customization_apps;installapps
fi

}

# bootloader?
bootloader() {
lsblk -lno NAME,TYPE | grep 'disk' | awk '{print "/dev/" $1 " " $2}' | sort -u > devices.txt
sed -i 's/\<disk\>//g' devices.txt
devices=` awk '{print "FALSE " $0}' devices.txt `
#grub=$()
msg q "Deseja instalar o gerenciador de inicialização?\n\nA resposta para isso geralmente é 'Sim',\n\nA menos que você esteja fazendo uma inicialização dupla e\ntenha outra opção para a inicialização."
grb="$rtm"
if [ "$grb" = "0" ]
	then 
	msg l
	grub_device=$($rtm "Onde você deseja instalar o bootloader? " --column Selecione --column Device $devices)
    msg q "Você tem outros sistemas operacionais em seu dispositivo?\n\nGostaria que o grub detectasse?"
    probe="$rtm"
fi
}

# Installation
installing() {
msg q "Clique em 'Sim' para iniciar a instalação.\n\nClique em 'Não' para abortar a instalação.\n\nTodos os pacotes serão baixados do zero, portanto a instalação\npode levar varios minutos."

if [ "$rtm" = "1" ]
	then exit
else (

# updating pacman cache
echo "# Atualizando Pacman Cache..."
echo "5"
pacman -Syy
arch_chroot "pacman -Syy"

#installing base
echo "# Instalando o pacote Arch Base..."
echo "10"
pacstrap /mnt base bash nano vim-minimal vi linux-firmware cryptsetup e2fsprogs findutils gawk inetutils iproute2 jfsutils licenses linux-firmware logrotate lvm2 man-db man-pages mdadm pciutils procps-ng reiserfsprogs sysfsutils xfsprogs usbutils dosfstools mtools
if [ "$kernel" = "linux" ]
	then pacstrap /mnt base base-devel linux
elif [ "$kernel" = "linux-lts" ]
	then pacstrap /mnt base linux-lts base-devel
elif [ "$kernel" = "linux-hardened" ]
	then pacstrap /mnt base linux-hardened base-devel
elif [ "$kernel" = "linux-zen" ]
	then pacstrap /mnt base linux-zen base-devel

fi

#generating fstab
echo "# Gerando tabela de sistema de arquivos..."
genfstab -p /mnt >> /mnt/etc/fstab
if grep -q "/mnt/swapfile" "/mnt/etc/fstab"; then
sed -i '/swapfile/d' /mnt/etc/fstab
echo "/swapfile		none	swap	defaults	0	0" >> /mnt/etc/fstab
fi
echo "20"
# installing video and audio packages
echo "# Instalando o desktop, drivers de som e vídeo..."
pacstrap /mnt mesa xorg xorg-server xorg-apps xorg-xinit xorg-twm xterm xorg-drivers alsa-utils pulseaudio pulseaudio-alsa intel-ucode b43-fwcutter networkmanager nm-connection-editor network-manager-applet polkit-gnome ttf-dejavu gnome-keyring xdg-user-dirs gvfs
echo "30"
# virtualbox
if [ "$vb" = "0" ]
	then
	if [ "$kernel" = "linux" ]
		then pacstrap /mnt virtualbox-guest-utils
        	echo -e "vboxguest\nvboxsf\nvboxvideo" > /mnt/etc/modules-load.d/virtualbox.conf
	elif [ "$kernel" = "linux-lts" ]
		then pacstrap /mnt virtualbox-guest-dkms virtualbox-guest-utils linux-lts-headers
		echo -e "vboxguest\nvboxsf\nvboxvideo" > /mnt/etc/modules-load.d/virtualbox.conf
	elif [ "$kernel" = "linux-hardened" ]
		then pacstrap /mnt virtualbox-guest-dkms virtualbox-guest-utils linux-hardened-headers
		echo -e "vboxguest\nvboxsf\nvboxvideo" > /mnt/etc/modules-load.d/virtualbox.conf
	elif [ "$kernel" = "linux-zen" ]
		then pacstrap /mnt virtualbox-guest-dkms virtualbox-guest-utils linux-zen-headers
		echo -e "vboxguest\nvboxsf\nvboxvideo" > /mnt/etc/modules-load.d/virtualbox.conf
	fi
fi
echo "40"

# installing chosen desktop
if [ "$desktops" = "Mais window managers" ]
then pacstrap /mnt $wm
else pacstrap /mnt $desktops
fi
echo "50"
# cups
if [ "$cp" = "0" ]
	then pacstrap /mnt ghostscript gsfonts system-config-printer gtk3-print-backends cups cups-pdf cups-filters
arch_chroot "systemctl enable org.cups.cupsd.service"
fi

# enabling network manager
arch_chroot "systemctl enable NetworkManager"
echo "60"

# adding chaoticrepo
#if [ "$rr" = "0" ]
#then 
#echo -e "\n[chaoticrepo]" >> /mnt/etc/pacman.conf;echo "SigLevel = Optional TrustAll" >> /mnt/etc/pacman.conf;echo "Server = https://mirrors.fossho.st/garuda/repos/chaotic-aur/x86_64".>> /mnt/etc/pacman.conf;echo -e "Server = https://mirrors.fossho.st/garuda/repos/chaotic-aur/x86_64\n".>> /mnt/etc/pacman.conf
#arch_chroot "pacman -Syy"
#fi

# installing pamac-aur
if [ "$pm" = "0" ]
then echo -e "\n[chaotic-aur]" >> /mnt/etc/pacman.conf;echo "SigLevel = Optional TrustAll" >> /mnt/etc/pacman.conf;echo -e "Server = https://mirrors.fossho.st/garuda/repos/chaotic-aur/x86_64\n" >> /mnt/etc/pacman.conf

pacman -Syy 
arch_chroot "pacman -Syy"
arch_chroot "pacman -S --noconfirm $pack"
fi

#multilib
if [ "$multilib" = "0" ]
then
echo -e "\n[multilib]" >> /mnt/etc/pacman.conf;echo -e "Include = /etc/pacman.d/mirrorlist\n" >> /mnt/etc/pacman.conf
fi

# AUR
if [ "$abs" = "0" ]
	then if [ "$pm" = "0" ]
		 then arch_chroot "pacman -Syy"
		 	  arch_chroot "pacman -S --noconfirm yay"
	else 
#	echo -e "\n[chaotic_aur]" >> /mnt/etc/pacman.conf;echo "SigLevel = Optional TrustAll" >> /mnt/etc/pacman.conf;echo -e "Server = https://mirrors.fossho.st/garuda/repos/chaotic-aur/x86_64\n" >> /mnt/etc/pacman.conf
	arch_chroot "pacman -Syy"
	arch_chroot "pacman -S --noconfirm yay"
	fi
fi
echo "70"

# installing bootloader
proc=$(grep -m1 vendor_id /proc/cpuinfo | awk '{print $3}')
if [ "$proc" = "GenuineIntel" ]
then pacstrap /mnt intel-ucode
elif [ "$proc" = "AuthenticAMD" ]
then arch_chroot "pacman -R --noconfirm intel-ucode"
pacstrap /mnt amd-ucode
fi
if [ "$grb" = "0" ]
	then if [ "$probe" = "0" ]
		then pacstrap /mnt os-prober
		fi 
		if [ "$SYSTEM" = 'BIOS' ]
		then echo "# Instalando o Bootloader..."
		pacstrap /mnt grub
		arch_chroot "grub-install --target=i386-pc $grub_device"
		arch_chroot "grub-mkconfig -o /boot/grub/grub.cfg"
	else
		echo "# Instalando o Bootloader..."


		if [ "$ans" = "Automatic Partitioning" ]
			then root_part=${dev}2
		fi

		[[ $(echo $root_part | grep "/dev/mapper/") != "" ]] && bl_root=$root_part \
		|| bl_root=$"PARTUUID="$(blkid -s PARTUUID ${root_part} | sed 's/.*=//g' | sed 's/"//g')

		arch_chroot "bootctl --path=/boot install"
		echo -e "default  Arch\ntimeout  10" > /mnt/boot/loader/loader.conf
		[[ -e /mnt/boot/initramfs-linux.img ]] && echo -e "title\tArch Linux\nlinux\t/vmlinuz-linux\ninitrd\t/initramfs-linux.img\noptions\troot=${bl_root} rw" > /mnt/boot/loader/entries/Arch.conf
		[[ -e /mnt/boot/initramfs-linux-lts.img ]] && echo -e "title\tArchLinux LTS\nlinux\t/vmlinuz-linux-lts\ninitrd\t/initramfs-linux-lts.img\noptions\troot=${bl_root} rw" > /mnt/boot/loader/entries/Arch-lts.conf
		[[ -e /mnt/boot/initramfs-linux-hardened.img ]] && echo -e "title\tArch Linux hardened\nlinux\t/vmlinuz-linux-hardened\ninitrd\t/initramfs-linux-hardened.img\noptions\troot=${bl_root} rw" > /mnt/boot/loader/entries/Arch-hardened.conf
		[[ -e /mnt/boot/initramfs-linux-zen.img ]] && echo -e "title\tArch Linux Zen\nlinux\t/vmlinuz-linux-zen\ninitrd\t/initramfs-linux-zen.img\noptions\troot=${bl_root} rw" > /mnt/boot/loader/entries/Arch-zen.conf
		fi
fi

# running mkinit
echo "# Executando o mkinitcpio..."
arch_chroot "mkinitcpio -p $kernel"
echo "80"

# installing chosen software
echo "# Instalando pacotes de software escolhidos..."
# Making Variables from Applications Lists
int=` cat int2.txt `
med=` cat med2.txt `
off=` cat off2.txt `
utils=` cat utils.txt `
cust=` cat cust.txt `


# Installing Selecting Applications
arch_chroot "pacman -Syy"
arch_chroot "pacman -S --noconfirm $int $med $off $utils $cust"
if [ "$lbr" = "0" ]
then arch_chroot "pacman -S --noconfirm libreoffice-$lover $lolang"
fi
if [ "$frf" = "0" ]
then arch_chroot "pacman -S --noconfirm firefox  $fflang"
fi
echo "90"

#root password
echo "# Configurando senha de root..."
touch .passwd
echo -e "$rtpasswd\n$rtpasswd2" > .passwd
arch_chroot "passwd root" < .passwd >/dev/null
rm .passwd

#adding user
echo "# Configurando o novo usuário..."
arch_chroot "useradd -m -g users -G adm,lp,wheel,power,audio,video -s /bin/bash $username"
touch .passwd
echo -e "$userpasswd\n$userpasswd2" > .passwd
arch_chroot "passwd $username" < .passwd >/dev/null
rm .passwd

#setting locale
echo "# Gerando o Locale..."
echo "LANG=\"${locale}\"" > /mnt/etc/locale.conf
echo "${locale} UTF-8" > /mnt/etc/locale.gen
arch_chroot "locale-gen"
export LANG=${locale}

#setting keymap
mkdir -p /mnt/etc/X11/xorg.conf.d/
echo -e 'Section "InputClass"\n\tIdentifier "system-keyboard"\n\tMatchIsKeyboard "on"\n\tOption "XkbLayout" "'$layout'"\n\tOption "XkbModel" "'$model'"\n\tOption "XkbVariant" ",'$variant'"\n\tOption "XkbOptions" "grp:alt_shift_toggle"\nEndSection' > /mnt/etc/X11/xorg.conf.d/00-keyboard.conf
if [ "$map" = "1" ]
then echo KEYMAP=$keymap >> /mnt/etc/vconsole.conf
fi

#setting timezone
echo "# Definindo fuso horário..."
arch_chroot "rm /etc/localtime"
arch_chroot "ln -s /usr/share/zoneinfo/${zone}/${subzone} /etc/localtime"

#setting hw clock
echo "# Configurando o relógio do sistema..."
arch_chroot "hwclock --systohc --$clock"
#arch_chroot "timedatectl set-timezone America/Sao_Paulo"
#arch_chroot "timedatectl set-ntp true"
#setting hostname
echo "# Configurando o nome do host..."
arch_chroot "echo $hname > /etc/hostname"

# setting n permissions
echo "%wheel ALL=(ALL) ALL" >> /mnt/etc/sudoers

# selecting shell
if [ "$shell" = "zsh" ]
then arch_chroot "pacman -S --noconfirm zsh zsh-syntax-highlighting zsh-completions grml-zsh-config;chsh -s /usr/bin/zsh $username"
elif [ "$shell" = "bash" ]
then arch_chroot "pacman -S --noconfirm bash;chsh -s /bin/bash $username"
elif [ "$shell" = "fish" ]
then arch_chroot "pacman -S --noconfirm fish;chsh -s /usr/bin/fish $username"
fi
echo "95"

# starting desktop manager
if [ "$dm"  = "default" ]
then if [ "$desktop" == "gnome" ]
	then arch_chroot "systemctl enable gdm.service"
	elif [ "$desktop" = "budgie-desktop" ]
	then pacstrap /mnt lxdm-gtk3 gnome-control-center gnome-backgrounds;arch_chroot "systemctl enable lxdm.service"
	elif [ "$desktop" = "lxde" ]
	then pacstrap /mnt lxdm-gtk3;arch_chroot "systemctl enable lxdm.service"
	elif [ "$desktop" == "plasma" ]
	then pacstrap /mnt sddm;arch_chroot "systemctl enable sddm.service"
	else pacstrap /mnt lxdm-gtk3
	arch_chroot "systemctl enable lxdm.service"
	fi
elif [ "$dm" = "lightdm" ]
then pacstrap /mnt lightdm lightdm-slick-greeter lightdm-settings accountsservice;arch_chroot "systemctl enable lightdm.service;echo -e '\n[LightDM]\nlogind-check-graphical=true >> /etc/lightdm.conf'"
else pacstrap /mnt $dm;arch_chroot "systemctl enable $dm.service"
fi

# unmounting partitions
umount -R /mnt
echo "100"
echo "# Instalação Terminada!"
) | zenity --progress --percentage=0 --title="$title" --width=450 --no-cancel
fi
}

# execution
# System Detection
if [[ -d "/sys/firmware/efi/" ]]; then
      SYSTEM="UEFI"
      else
      SYSTEM="BIOS"
fi

arch_chroot() {
    arch-chroot /mnt /bin/bash -c "${1}"
}

Parted() {
	parted --script $dev "$1"
}
#
final() {
ans=$(zenity --list --title="$title" --radiolist --text "O que voce gostaria de fazer Agora?" --column "Selecione" --column "Opção" FALSE Reiniciar FALSE Fechar)
	if [ "$ans" = "Reiniciar" ]
	then reboot
	else exit
	fi
}
#
greeting
# function to check for an active internet connection
if [[ ! $(ping -c 1 google.com) ]]; then
     msg i "A conexão com a Internet não foi detectada, por favor, tente novamente ."
     ./$(basename $0) && exit 
   	 #this will run if started from the same folder
fi
#
pulling
partition
configure
root_password
user_password
changeshell
kernel
vbox
#nvidia
#revengerepo
multilib
packagemanager
archuserrepo
cups
displaymanager
desktop
#update
firefox
libreoffice
installapps
bootloader
installing
final