#!/bin/bash
#
# update-guestfs-appliance: download and install a guestfs binary appliance
# Copyright (C) 2013 Nikos Skalkotos <skalkoto@gmail.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.

VERSION=1.32.0
SHA512SUM="202d0dde45612f9ef45cdb73cd4aeba6c75dcd52790e7f156b2ff404616887af4019e5bd061e3c6607f4f96ac136132c31d180dda31a71bfb31ade5da508b832"

set -e
umask 022

if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root" >&2
    exit 1
fi

echo >&2
echo "Downloading binary appliance v$VERSION for libguestfs ... " >&2
echo >&2

# Cache file to avoid redownloading it on a second run
mkdir -p /var/cache/guestfs
cd /var/cache/guestfs
silent=
if [ ! -t 1 ]; then
    echo "Output is not a TTY, not outputting progress (be patient!)" >&2
    silent=-nv
fi
wget $silent --continue -O appliance-${VERSION}.tar.xz \
    http://libguestfs.org/download/binaries/appliance/appliance-${VERSION}.tar.xz

echo -n "Checking checksum ... " >&2
echo "$SHA512SUM appliance-${VERSION}.tar.xz" | sha512sum -c

echo >&2
echo "Extracting binary appliance files to /usr/lib/guestfs:" >&2
tar -xvf appliance-${VERSION}.tar.xz -C /usr/lib/guestfs \
    --no-same-owner --strip-components=1

echo "Correcting permissions:" >&2
chmod -v 644 "/usr/lib/guestfs/"{kernel,initrd,root,README.fixed}

echo >&2
echo "Binary appliance installation finished successfully!" >&2
