#!/bin/bash
# Test a remote machine such as Fedora, RHEL, SLES
#

# On RHEL 7.3+
# for ssh access edit pam.d files to avoid root login by ssh to fail with uid < 1000
# Install on it perl perl-Data-Dumper and perl-YAML
# setup that VM with pb -p pb -m $DISTRO sbx2setupvm
# setup that VM after with pb -p mondorescue -m $DISTRO prepvm
#
#DISTRO=sles-15-x86_64
DISTRO=sles-12-x86_64
#DISTRO=rhel-8-x86_64
#DISTRO=rhel-7-x86_64
#DISTRO=rhel-5-x86_64
#DISTRO=fedora-20-x86_64

NAME=`pbdistrocheck $DISTRO | grep -E '^Name:' | awk '{print $2}'`
VER=`pbdistrocheck $DISTRO | grep -E '^Ver:' | awk '{print $2}'`
ARCH=`pbdistrocheck $DISTRO | grep -E '^Arch:' | awk '{print $2}'`
D=$DISTRO
DEST=/users/mondo/small
DIR=images
TEMP=temp
CACHE=cache
MNT=/mnt2
KEY=$HOME/.ssh/pb_rsa
PORT=`ps auxww | grep qemu | grep -w $D | grep -v grep | perl -p -e 's|.*127.0.0.1:([0-9]+)-:.*|$1|'`
if [ _"$PORT" == _"" ]; then
	pb -p mondorescue -r branches/3.3 -m $D launchvm
fi

pb -p mondorescue -r branches/3.3 -m $D sbx2vm MondoRescue mondo mindi mindi-busybox
cat > /tmp/test << EOF
#!/bin/bash
#
if [ $NAME = "rhel" ]; then
	REPODIR="/etc/yum.repos.d"
	REPOCMD="yum"
elif [ $NAME = "sles" ]; then
	REPODIR="/etc/zypp/repos.d"
	REPOCMD="zypper --gpg-auto-import-keys --non-interactive"
fi
\$REPOCMD install -y curl
cd \$REPODIR
if [ ! -f \$REPODIR/mondorescue.repo ]; then
	curl ftp://ftp.mondorescue.org/$NAME/$VER/$ARCH/mondorescue.repo -o mondorescue.repo
fi
if [ ! -f \$REPODIR/mondorescue-test.repo ]; then
	curl ftp://ftp.mondorescue.org/test/$NAME/$VER/$ARCH/mondorescue-test.repo -o mondorescue-test.repo
fi
if [ $NAME = "rhel" ]; then
	rpm -q epel-release
	if [ \$? -ne 0 ]; then
		dnf install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$VER.noarch.rpm
	fi
	\$REPOCMD makecache 
elif [ $NAME = "sles" ]; then
	\$REPOCMD ref
fi
\$REPOCMD install -y nfs-utils
# To take test repo first do it that way
\$REPOCMD install -y mindi
\$REPOCMD install -y mondo
\$REPOCMD update -y mondo mindi perl-MondoRescue mindi-busybox
rpm -aq | grep -Ei 'mondo|mindi'
modprobe nfsv3
mkdir -p $MNT
mount -o vers=3 10.0.2.2:$DEST $MNT
mkdir -p $MNT/$DIR $MNT/$TEMP $MNT/$CACHE
mondoarchive -N -G -K 99 -E '/home|/var/log|/usr/share/doc|/usr/src|/usr/share/texmf|/mnt|/mnt2' -s 4480m -n 10.0.2.2:$DEST -d $DIR -p $D -z -O -S $MNT/$CACHE -T $MNT/$TEMP 
umount $MNT/
EOF
# Now should be OK
PORT=`ps auxww | grep qemu | grep -w $D | grep -v grep | perl -p -e 's|.*127.0.0.1:([0-9]+)-:.*|$1|'`

ssh -i $KEY -p $PORT root@localhost "rm -rf ./test"
scp -i $KEY -P $PORT /tmp/test root@localhost:
ssh -i $KEY -p $PORT root@localhost "chmod 755 ./test ; sh -x ./test"

sudo chown bruno $DEST/temp
Q=$DEST/temp/test.qemu
qemu-img create -f qcow2 $Q 7G
cmd="qemu-kvm -m 2048 -boot d -cdrom $DEST/$DIR/$D-1.iso $Q"
echo "Calling restore test: $cmd"
$cmd
