#!/bin/bash
set -e

# install-arch.sh - installs arch in a chroot
# ed <irc.rizon.net>, MIT-licensed, 2019-05-15, v1.0
# https://ocv.me/dev/?install-arch.sh


##
## config

# chroot location
cr="/c/arch"

# url to download bootstrap from, expects <URL>.sig to exist as well
bootstrap_url="https://mirror.leaseweb.net/archlinux/iso/latest/"

# https://www.archlinux.org/master-keys/
keys() { cat <<'EOF'
4AA4 767B BC9C 4B1D 18AE  28B7 7F2D 434B 9741 E8AC
EOF
}


##
## helper methods

msg() { printf '\033[1;30m>\033[0;34m>\033[1m>\033[0m %s\n' "$1" >&2; }
inf() { printf '\n\033[1;30m>\033[0;32m>\033[1m>\033[0;32m %s\033[0m\n' "$1" >&2; }
wrn() { printf '\n\033[1;30m>\033[0;33m>\033[1m>\033[0;33m %s\033[0m\n' "$1" >&2; }
err() { printf '\n\033[1;30m>\033[0;31m>\033[1m>\033[0;31m %s\033[0m\n' "$1" >&2; }

# ensure no trailing slash in the chroot path
cr="${cr%/}"

# check that it's safe to continue
[ -e "$cr" ] &&
{
	err "chroot exists, aborting"
	exit 1
}


##
## add all missing gpg keys

keys | while IFS= read -r x
do
	gpg --list-keys "$x" >/dev/null &&
		msg "key [$x] ok" ||
	{
		msg "key [$x] being added..."
		gpg --recv-keys "$x"
		echo
	}
done


##
## determine bootstrap filename and download it

bootstrap_line="$(
	wget -qO- "$bootstrap_url"/sha1sums.txt |
	tee /dev/shm/arch.sum |
	grep -E '[^ ]+  archlinux-bootstrap-.*\.tar.gz$'
)" ||
{
	err "failed to determine bootstrap filename"
	exit 1
}

bootstrap_sha="${bootstrap_line%% *}"
bootstrap_fn="${bootstrap_line##* }"

inf "using bootstrap [$bootstrap_fn]"

shachk() {
	printf '%s  %s\n' "$bootstrap_sha" "$bootstrap_fn" | sha1sum -c
}

shachk &&
	inf "sha1sum ok, skip download" ||
{
	msg "sha1sum fail, downloading..."
	wget "$bootstrap_url$bootstrap_fn"
	shachk
}


##
## gpg-verify bootstrap and collect the key it was signed with

key="$(
	gpg --verify "$bootstrap_fn".sig 2>&1 |
	tee /dev/shm/gpgtmp |
	awk '
		BEGIN {ok=0;nkeys=0}
		/^gpg: Good signature from "/ {ok=1}
		/^gpg: +using RSA key / {nkeys++;key=$5}
		END {print key; if (nkeys==1 && ok==1) exit 0; exit 1}
	'
	
	echo "${PIPESTATUS[*]}" |
	grep -qE '^0 0 0$'
)" &&
	inf "gpg verification approves of the archive" ||
{
	err "gpg verification rejected the archive"
	exit 1
}


##
## check if that was one of the expected keys

ok=0
while IFS= read -r goodkey
do
	[ "$goodkey" = "$key" ] &&
		ok=1
done < <(
	keys |
	tr -d ' ' |
	tr '[:lower:]' '[:upper:]'
)

[ $ok -eq 1 ] &&
	inf "collected key is known" ||
{
	err "the key was unexpected: $key"
	exit 1
}


##
## unpack

echo
msg "unpacking to:  $cr"

mkdir -p "$cr"
tar -xC"$cr" --strip-components=1 -f"$bootstrap_fn"

inf "nice"
