#!/bin/bash
#
# Copyright (C) 2015 Red Hat Inc.
# Author: <marius.vollmer@redhat.com>
#
# This program 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 2 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA.

set -ex

if [ "$#" -lt 3 ]; then
    echo >&2 "Usage: virt-builder-fedora IMAGE OS ARCH [SUBSCRIPTION_PATH]"
    exit 1
fi

subscription_args=""

# If we have subscription details as an arg, upload those into the vm
# Otherwise ensure subscription is skipped during setup
if [ "$#" -gt 3 ]; then
    subscription_path=$4
    subscription_args="--mkdir /root/.rhel \
      --upload $subscription_path/login:/root/.rhel/login \
      --upload $subscription_path/pass:/root/.rhel/pass"
else
    subscription_args="--write /root/.skip_repos:"
fi

BASE=$(dirname $0)

out=$1
os=$2
arch=$3
test -z "$BOOTSTRAP_VOLUME_SIZE" && BOOTSTRAP_VOLUME_SIZE="8G"

if [ "$VIRT_BUILDER_NO_CACHE" == "yes" ]; then
    virt_builder_caching="--no-cache"
fi

# we can't use virt-builder --ssh-inject until all our target systems support this

virt-builder "$os" \
             $virt_builder_caching \
             --output "$out" \
             --size $BOOTSTRAP_VOLUME_SIZE \
             --format qcow2 \
             --arch "$arch"\
             --root-password password:foobar \
             --mkdir /root/.ssh \
             --chmod 0700:/root/.ssh \
             --upload $BASE/../../common/identity.pub:/root/.ssh/authorized_keys \
             --chmod 0600:/root/.ssh/authorized_keys \
             --run-command 'chown root:root /root/.ssh/authorized_keys' \
             --upload $BASE/host_key:/etc/ssh/ssh_host_rsa_key \
             --chmod 0600:/etc/ssh/ssh_host_rsa_key \
             --upload $BASE/host_key.pub:/etc/ssh/ssh_host_rsa_key.pub \
             --upload $BASE/fedora-network-ifcfg:/etc/sysconfig/network-scripts/ifcfg-eth0 \
             --delete /etc/systemd/system/multi-user.target.wants/sshd.service \
             --mkdir /etc/systemd/system/sockets.target.wants \
             --link /usr/lib/systemd/system/sshd.socket:/etc/systemd/system/sockets.target.wants \
             --selinux-relabel \
             $subscription_args
