#!/bin/bash

exec > >(tee -a "/tmp/linux_inst.log") 2>&1
msg_print note "linux_inst start log"

if [[ $arch == $debian_arch ]]; then
  arch_chroot_command="chroot_rootfs auto"
else
  parse_arch "$qemu_arch"
  if qemu_chroot check $qemu_arch ok; then
    arch_chroot_command="qemu_chroot $qemu_arch"
  else
    exit 1
  fi
fi
if [[ $repo_mode == "local" ]]; then
	if [[ -n "$pubkey" ]]; then
		if is_url "${pubkey}"; then
		    wget -O /tmp/pubkey.asc "$pubkey" || error_msg="Couldn't download $pubkey."
		else
		    cp -a "$pubkey" /tmp/pubkey.asc || error_msg="Couldn't copy $pubkey."
		fi
		gpg --import /tmp/pubkey.asc
		GPGKEY=`gpg --list-keys | grep /root/`
		if [[ -n "$GPGKEY" ]]; then
			deb_add_option="$deb_add_option --keyring=${GPGKEY}"
		fi
	fi
else
	if [[ -n "$gpgkey" ]]; then
		if is_url "${gpgkey}"; then
		    wget -O /tmp/gpgkey.gpg "$gpgkey" || error_msg="Couldn't download $gpgkey."
		else
		    cp -a "$gpgkey" /tmp/gpgkey.gpg || error_msg="Couldn't copy $gpgkey."
		fi
		if [[ -f "/tmp/gpgkey.gpg" ]]; then
			deb_add_option="$deb_add_option --keyring=/tmp/gpgkey.gpg"
		fi
	fi
fi

[[ $debian_arch != $arch ]] && deb_add_option="$deb_add_option --foreign"
[[ -z $preinstall ]] || preinstall=",$preinstall"
debootstrap_component="${debian_repos_order[0]}"
msg_print note "debootstrap_component=[${debootstrap_component}]  debian_repos[${debootstrap_component}]=[${debian_repos[${debootstrap_component}]}]"
msg_print note "bash -c debootstrap --arch arch[${arch}] deb_add_option[${deb_add_option}] --include=gnupg$preinstall $version_debian dir[${dir}] \"$(echo "${debian_repos[$debootstrap_component]}" | cut -d" " -f2)\""
bash -c "debootstrap --arch $arch $deb_add_option --include=gnupg$preinstall $version_debian $dir \"$(echo "${debian_repos[${debootstrap_component}]}" | cut -d" " -f2)\""
msg_print note "[[ debian_arch[${debian_arch}] != arch[${arch}] ]] && arch_chroot_command[${arch_chroot_command}] dir[${dir}] /debootstrap/debootstrap --second-stage"
[[ $debian_arch != $arch ]] && $arch_chroot_command $dir /debootstrap/debootstrap --second-stage

if [[ $repo_mode == "local" ]]; then
	if [[ -f "/tmp/pubkey.asc" ]]; then
		cp -p /tmp/pubkey.asc "${dir}/root/"
	fi
else
	if [[ -f "/tmp/gpgkey.gpg" ]]; then
		cp -p /tmp/gpgkey.gpg "${dir}/root/"
	fi
fi
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
source ./lib/common/common_actions_1.sh

if [[ $OP_MODE == "debug" ]]; then
	msg_print note "debug for $arch_chroot_command dir[$dir] bash /root/pi_s1.sh"
	echo "root:${root_passwd}" | chpasswd -c SHA512
	msg_print note "`ip a`"
else
	msg_print note "$arch_chroot_command dir[$dir] bash /root/pi_s1.sh"
	$arch_chroot_command "$dir" bash /root/pi_s1.sh  2>&1 | tee ${SETUPLOG}
	cp -p /tmp/*  "${dir}/root/"
	rm -rf "$dir/root/pi_s1.sh" "$dir/root/configuration" "$dir/root/alexpro100_lib.sh" "$dir/root/LI_certs"
fi  
