#!/bin/bash -efu

topdir="$(readlink -ev "$0")"
topdir="${topdir%/*/*}"

. "$topdir/testing/sh-functions"

readonly VENDOR=altlinux
readonly ARCH=x86_64
readonly IMAGE=alt:sisyphus
readonly KERNEL_FLAVOR=-std-def

. "$topdir/testing/packages-$VENDOR"

MAKE_INITRD_PACKAGES+=" fuse-sshfs"

TESTNAME="$1"; shift

KICKSTART_DISKS=0
BOOT_DISKS=0
BOOT_CMDLINE="console=ttyS0,115200n8 fastboot rw"

eval $(sed -n -e 's/^# param //p' "$topdir/testing/$TESTNAME.cfg")

BOOT_APPEND="$BOOT_CMDLINE"

readonly builddir=/srv

readonly workdir="testing/cache/$VENDOR/$TESTNAME"
readonly logdir="testing/logs/$VENDOR/$TESTNAME"
readonly statusdir="$topdir/testing/status"

readonly top_workdir="$topdir/$workdir"
readonly top_logdir="$topdir/$logdir"

prepare_testsuite

if [ ! -d "$top_workdir/.ssh" ]; then
	mkdir -p -m 700 -- "$top_workdir/.ssh"
	ssh-keygen -t rsa -f "$top_workdir/.ssh/id_rsa" -N ''
fi

for step in "$@"; do
	case "$step" in
		build-git)
			gh_group_start "building from git tree"

			cat_exec "$top_workdir/run.sh" <<-EOF
			#!/bin/bash -efux

			apt-get -y -qq update
			apt-get -y -qq install $MAKE_INITRD_PACKAGES_DEVEL

			cd "$builddir"
			rc=0

			./autogen.sh
			./configure \
				--enable-local-build \
				--with-runtimedir=/lib/initrd1 || rc=\$?

			if [ "\$rc" != 0 ]; then
				echo '========================================='
				cat config.log
				exit 1
			fi

			make || rc=\$?

			if [ "\$rc" != 0 ]; then
				echo '========================================='
				cat config.log
				exit 1
			fi
			EOF

			run podman run --rm -ti \
				--volume="$topdir:$builddir" \
				"$IMAGE" "$builddir/$workdir/run.sh"

			gh_group_end
			;;
		build-sysimage)
			[ -n "${SYSIMAGE_PACKAGES-}" ] ||
				continue

			if [ -z "$(podman images -an --format='1' -f reference=localhost/mi-$TESTNAME-$VENDOR:sysimage)" ]; then
				gh_group_start "creating sysimage"

				run podman image build \
					-t "localhost/mi-$TESTNAME-$VENDOR:sysimage" \
					--pull --squash --force-rm=true \
					-f - <<-EOF
				FROM $IMAGE
				RUN rpm -ql filesystem | xargs -r mkdir -p
				RUN apt-get -y -qq update
				RUN apt-get -y -qq install $SYSIMAGE_PACKAGES
				RUN apt-get -y -qq clean
				RUN \
				 find /usr/share/license /usr/share/license-exception -delete; \
				 find /usr/share/locale/ -mindepth 3 -maxdepth 3 -type f -name '*.mo' -delete; \
				 find /usr/share/doc/ /usr/share/man/ /usr/share/info/ -mindepth 1 -delete; \
				 find /var/lib/apt/lists/ /var/cache/apt/ -type f -delete;
				RUN \
				 printf >> /etc/sysconfig/init '%s\n' \
				   'REMOUNT_ROOTFS_RW_COMMAND=/bin/true'
				RUN \
				 printf > /sbin/init.once '%s\n' \
				   '#!/bin/sh' \
				   'echo; echo;' \
				   'echo "IT WORKS!";' \
				   'echo; echo;' \
				   'echo i > /proc/sysrq-trigger;' \
				   'echo s > /proc/sysrq-trigger;' \
				   'echo b > /proc/sysrq-trigger;' \
				   ; \
				 chmod 755 /sbin/init.once
				RUN \
				 printf > /etc/rc.d/init.d/halt '%s\n' \
				   '#!/bin/sh' \
				   'exec /sbin/poweroff -d -f -i -k'; \
				 chmod 755 /etc/rc.d/init.d/halt
				RUN \
				 echo 'z0:3:once:/sbin/init.once' >>/etc/inittab;
				RUN find / -xdev \
				 -type f \
				 -a '(' -perm -550 -o -perm -500 ')' \
				 -a '!' -perm -005 \
				 -exec chmod g+rx,a+rx '{}' '+'
				RUN find / -mindepth 2 -xdev -type d -exec chmod 777 '{}' '+'
				EOF

				gh_group_end
			fi

			gh_group_start "adding make-initrd binaries"

			run podman run --rm -ti \
				--mount="type=image,src=localhost/mi-$TESTNAME-$VENDOR:sysimage,dst=/image" \
				--mount="type=tmpfs,destination=/image$builddir" \
				--mount="type=bind,src=$topdir/.build/dest,dst=/image$builddir/.build/dest" \
				--mount="type=bind,src=$topdir/data,dst=/image$builddir/data" \
				--mount="type=bind,src=$topdir/features,dst=/image$builddir/features" \
				--mount="type=bind,src=$topdir/guess,dst=/image$builddir/guess" \
				--mount="type=bind,src=$topdir/tools,dst=/image$builddir/tools" \
				--volume="$topdir:/host" \
				"$IMAGE" tar -C /image -cf /host/$workdir/sysimage.tar .

			gh_group_end

			if [ -d "$top_workdir/sysimage" ]; then
				find "$top_workdir/sysimage" -type d -exec chmod +w '{}' '+'
				find "$top_workdir/sysimage" -delete
			fi
			mkdir -p -- "$top_workdir/sysimage"

			tar -xf "$top_workdir/sysimage.tar" -C "$top_workdir/sysimage"

			rm -f -- "$top_workdir/sysimage.tar"
			;;
		build-kickstart)
			;;
		build-tools)
			gh_group_start "building initramfs"

			cat_exec "$top_workdir/run.sh" <<-EOF
			#!/bin/bash -efux

			tee /etc/initrd.mk <<-EOF1
			 AUTODETECT = all
			 DISABLE_GUESS = root
			 FEATURES += sshfsroot qemu
			 SSHFS_KEY = $builddir/$workdir/.ssh/id_rsa
			EOF1

			cat > /etc/sysconfig/installkernel <<EOF1
			 INITRD_GENERATOR=make-initrd
			 MAKE_INITRD=$builddir/.build/dest/usr/sbin/make-initrd
			 MKINITRD=$builddir/.build/dest/usr/sbin/mkinitrd-make-initrd
			EOF1

			apt-get -y -qq update
			apt-get -y -qq install $MAKE_INITRD_PACKAGES
			apt-get -y -qq install $KERNEL_PACKAGES

			cp -L /boot/vmlinuz    $builddir/$workdir/sshfsroot-vmlinuz
			cp -L /boot/initrd.img $builddir/$workdir/sshfsroot-initrd.img
			EOF

			run podman run --rm -ti \
				--volume="$topdir:$builddir" \
				"$IMAGE" "$builddir/$workdir/run.sh"

			gh_group_end

			[ -n "${SSH_SERVER_PACKAGES-}" ] ||
				continue

			gh_group_start "building ssh server"

			cat > "$top_workdir/Dockerfile" <<-EOF
			FROM $IMAGE
			RUN apt-get -y -qq update
			RUN apt-get -y -qq install $SSH_SERVER_PACKAGES
			RUN apt-get -y -qq clean

			ADD .ssh/id_rsa.pub /etc/openssh/authorized_keys/sftp

			RUN \
			 printf >/etc/openssh/sshd_config '%s\n' \
			  "Port 2222" \
			  "ListenAddress 127.0.0.1" \
			  "Subsystem sftp internal-sftp"

			RUN \
			 printf >/etc/syslog.conf '%s\n' \
			  "*.* /dev/stdout"

			RUN \
			 printf >/endpoint '%s\n' \
			  "#!/bin/bash" \
			  "syslogd -n &" \
			  "useradd -m -U -p '' -s /bin/false sftp" \
			  "ssh-keygen -A" \
			  "exec /usr/sbin/sshd -D -d -e"; \
			 chmod 755 /endpoint

			ENTRYPOINT /endpoint
			EOF

			run podman image build \
				-t "localhost/mi-sshd:latest" \
				--pull --squash --force-rm=true \
				-f "$top_workdir/Dockerfile"

			gh_group_end
			;;
		run-kickstart)
			;;
		run-services)
			gh_group_start "running ssh server"

			run podman rm -i -f sshd

			run podman run --rm -ti --name="sshd" \
				--network=host \
				--volume="$top_workdir/sysimage:/data/incoming" \
				--volume="$topdir:$builddir" \
				"mi-sshd:latest" > "$top_logdir/sshd.log" 2>&1 &

			i=0
			while ! grep -qsF 'Server listening on 127.0.0.1 port 2222.' "$top_logdir/sshd.log"; do
				if [ "$i" = 10 ]; then
					run cat "$top_logdir/sshd.log"
					fatal "unable to run ssh server"
				fi
				message "waiting for ssh server ..."
				sleep 1
				i=$(($i+1))
			done
			gh_group_end
			;;

		run-boot)
			BOOT_KERNEL="$top_workdir/sshfsroot-vmlinuz"
			BOOT_INITRD="$top_workdir/sshfsroot-initrd.img"
			BOOT_LOGS="$top_logdir/sshd.log"

			gh_group_start "checking the ability to boot"

			qemu_setup_cpu
			qemu_exec

			gh_group_end
			;;
		*)
			fatal "unknown step: $step"
			;;
	esac
done
