#!/usr/bin/bash -x

# Create Copr builder image from the default Fedora Cloud image.
# Copyright (C) 2020 Red Hat, Inc.
#
# 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.

. "/usr/share/eimg"/lib || exit 1
. /etc/eimg/eimg.sh || exit 1

tmpdir=/tmp
orig_image=$1
image_type=${2-builder}
eimg_download_image "$orig_image"
image_wip=$(mktemp "$tmpdir/wip-image-XXXXX.qcow2")

export LIBGUESTFS_PATH=/tmp/libguestfs-fedora-appliance
/usr/bin/eimg-appliance-in-container "$LIBGUESTFS_PATH" || :

cleanup()
{
    rm -rf "$image_wip"
}
trap cleanup EXIT

key_name=$HOME/.ssh/id_rsa
test -f "$key_name" || {
    ssh-keygen -b 4096 -t rsa -f "$key_name" -q -N ""
}

cp -f "$eimg_download_image_result" "$image_wip"

run_playbook()
{
    # no playbook for the infra images
    test "$image_type" = infra && return 0
    EIMG_PLAYBOOK=$EIMG_COPR_PLAYBOOK EIMG_PLAYBOOK_DIR=$EIMG_COPR_PLAYBOOK_DIR \
    /usr/libexec/eimg-execute-playbook
}


/usr/bin/eimg-prep "$image_wip" \
    && /usr/bin/eimg-wait "$image_wip" \
    && EIMG_WAITED=: /usr/bin/eimg-update "$image_wip" \
    && run_playbook \
    && EIMG_WAITED=: /usr/bin/eimg-cleanup-online "$image_wip" \
    && /usr/libexec/eimg-stop "$image_wip" \
    && virt-sysprep -a "$image_wip" --root-password disabled "${EIMG_FINAL_SYSPREP_ARGS[@]}" \
    && /usr/bin/eimg-minimize "$image_wip"
