#!/bin/bash
#wget -O- http://its.alexunderboots.ru/i2.sh | bash /dev/stdin

DEPLOY='its.alexunderboots.ru'
export target_in=/tmp

add_line () {
grep -qxF "$1" $2 || echo "\n$1" >> $2
}
print_color () {
	echo $(tput setab 4)
	printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
	echo " "$1" "
	printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
	echo $(tput sgr 0) $'\n'
}
print_warning () {
	echo $(tput setab 1)
	printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
	echo -e " "$1" "
	printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
	echo $(tput sgr 0) $'\n'
}
error_fatal (){
	echo $(tput setab 1)
	printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
	echo " "$1" " | systemd-cat -t backups.sh -p emerg
	# stdout -> stderr
	#>&2 echo " "$1" "
	printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
	echo $(tput sgr 0) $'\n'
	exit 3
}
export -f add_line
export -f print_warning
export -f print_color
export -f error_fatal

apt update && apt-get install dialog curl

# Скопировать все скрипты локально
print_color "Копируем скрипты в tmp"
cd ${target_in}
rm -f /tmp/${DEPLOY}/_deploy/*.sh
wget -r -np --reject-regex '.*\.0$' --backups=0 -nv http://${DEPLOY}/_deploy/
#-nd -l 1 -A '*.sh'

# Почистить и разложить
target_in=/tmp/${DEPLOY}/_deploy
cd ${target_in}
find . -type f -not -name '*.sh' -exec chmod 666 {} +
find . -type f -name '*.sh' -exec chmod 777 {} +
find . -type f -name '*.html' -exec rm -f {} +
yes | cp -i -r ${target_in}/_root/* /root

# Выполнит все скрипты
if [[ "$#" -ne 1 ]]; then
	array=("$(ls i*.sh | awk '{print $1, "on"}')")
	echo ${array[@]}
	cmd=(dialog --stdout --no-items \
		--separate-output \
		--ok-label "Install" \
		--checklist "Select options:" 22 76 16)
	choices=$("${cmd[@]}" ${array})
	echo ""
	echo You choice: $choices
	for script in $choices ; do
		echo $script
		print_color $script
		rm -f $script.log
		bash ${target_in}/$script 2>&1 | tee -a $script.log
	done
	#	for script in ${target_in}/i*.sh ; do
#		print_color $script
#		rm -f $script.log
#		sh $script 2>&1 | tee -a $script.log
#	done
fi


print_warning 'Please manual run:\n
nano /etc/network/interfaces\n
nano /etc/wireguard/wg0.conf\n
nano /root/variable-sample.sh'
