#!/bin/bash
set -e -o pipefail

# Copyright (C) 2019 Gunter Miegel coinboot.io
#
# This file is part of Coinboot.
#
# Coinboot is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

# debug build +3

export RELEASE=$(date +'%Y%m%d')
export VERSION='0.98 Beta'

change_to_buildir (){
if [[ $(basename $PWD) != debirf ]] && ! id vagrant; then
  cd debirf
elif id vagrant; then
  cd /vagrant
fi
}

run_qemu() {
  zram=$1
  qemu-system-x86_64 \
  -kernel build/coinboot-vmlinuz-${KERNEL} \
  -initrd build/coinboot-initramfs-${KERNEL} \
  -m 4096 \
  -smp 2 \
  -display none \
  -daemonize \
  -net user,hostfwd=tcp::2022-:22 \
  -net nic \
  -append "console=ttyS0 \
           netconsole=6666@192.168.1.10/eth0,6666@192.168.1.1/9c:4a:c7:7a:a1:7a \
           net.ifnames=0 \
           biosdevname=0 \
           break=skip_loading_plugins \
           $zram"
 }

verify_over_ssh() {
  while ! nc -z 127.0.0.1 2022; do
  echo 'Waiting for Coinboot machine to listen on port 2222/SSH ...'
  sleep 10
  done

  while ! sshpass -p ubuntu ssh -o StrictHostKeyChecking=no -l ubuntu -p 2022 localhost "grep -C 10 $RELEASE /etc/motd && lsb_release -a && uname -a && df -B1 && free -b && zramctl -b" ; do
  echo 'Waiting for SSH login to succeed...'
  sleep 10
  done

  killall qemu-system-x86_64

  while nc -z 192.168.1.10 22; do
  echo 'Waiting for Coinboot machine to stop listen on port 22/SSH ...'
  sleep 10
  done
 }


sudo apt-get update

sudo apt-get  install --yes qemu-system-x86 ipxe-qemu sshpass

change_to_buildir

docker-compose up

run_qemu

verify_over_ssh

run_qemu zram

verify_over_ssh
