#!/bin/bash
# -*- coding: utf-8 -*-

# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

set -e

# The docker pool should grow automatically as needed, but we grow it
# explicitly here anyway.  This is hopefully more reliable.
# HACK: docker falls over regularly, print its log if it does
systemctl start docker || journalctl -u docker
lvresize atomicos/root        -l+50%FREE -r
lvresize atomicos/docker-pool -l+100%FREE

# we need cockpit/ws as well
docker pull cockpit/ws

# docker images that we need for integration testing
/var/lib/testvm/docker-images.setup

# fully upgrade host. Anything past this point can't touch /etc
# Upgrade host if there is a valid upgrade available (we might be on a RC)
if rpm-ostree upgrade --check; then
    atomic host upgrade
    # HACK - Find a better way to compute the ref.
    # https://lists.projectatomic.io/projectatomic-archives/atomic-devel/2016-July/msg00015.html

    remote=$(ostree remote list)
    ref=$(python -c 'import json; print json.load(open("/usr/share/rpm-ostree/treefile.json"))["ref"]')
    checkout="$remote:$ref"
else
    checkout=$(atomic host status --json | python -c 'import json; import sys; j = json.loads(sys.stdin.readline()); print [x for x in j["deployments"] if x["booted"]][0]["checksum"]')
fi

# Checkout the just upgraded os branch since we'll use it every time
# we build a new tree.

ostree checkout "$checkout" /var/local-tree

# reduce image size
/var/lib/testvm/zero-disk.setup

# Final tweaks
rm -rf /var/log/journal/*
