#!/usr/bin/bash

# Cleanup Fedora based cloud image.
# Copyright (C) 2015 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.

: ${prefix=/usr}

. "/usr/share/eimg"/lib

tempdir=`mktemp -d /tmp/build-vm-XXXXXX`
test -z "$tempdir" && die "can't create tempdir"
cleanup()
{
    rm -rf "$tempdir"
}
trap cleanup EXIT

/usr/bin/eimg-wait "$1" || exit 1

eimg_load_ip

## task to be done on running guest ##
eimg_remote_run 'rm -f /var/lib/random-seed'
eimg_remote_run 'rpm -e linux-firmware'
eimg_remote_run 'sync'
sync

# restart to boot against updated kernel
EIMG_WAITED=false /usr/libexec/eimg-stop || exit 1
EIMG_WAITED=false /usr/bin/eimg-wait "$1" || exit 1

eimg_load_ip
eimg_remote_run 'keep-one-kernel.sh'
for i in yum dnf yum-deprecated ; do
    eimg_remote_run "$i clean all"
done

# Drop the arg we need to locally start the image without config image, but that
# would later fool the boot with cloud-init.  Also revert back the configuration
# from fedora-kickstarts (cloud) that we removed in eimg-wait.
eimg_remote_run "grubby --update-kernel=ALL --remove-args=ds=nocloud-net --args 'no_timer_check net.ifnames=0 console=tty1 console=ttyS0,115200n8'"

eimg_remote_run "truncate -c -s 0 /var/log/$pkgmanager.log"
eimg_remote_run "truncate -c -s 0 /var/log/$pkgmanager.rpm.log"
eimg_remote_run 'rm -f /var/lib/rpm/__db*'
eimg_remote_run 'rm -rf /var/lib/cloud/*'
eimg_remote_run "mkdir -p /var/cache/$pkgmanager"
eimg_remote_run "truncate --size 0 /etc/resolv.conf"
eimg_remote_run '/usr/sbin/fixfiles -R -a restore'
eimg_remote_run 'dd if=/dev/zero of=/dd-fill'
eimg_remote_run 'btrfs filesystem sync / ; rm /dd-fill && sync ; btrfs filesystem sync /'

## shut down the guest ##
/usr/libexec/eimg-stop || exit 1
