#!/bin/bash

# Copyright 2016 Matthew Thode
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

if [ "${DIB_DEBUG_TRACE:-0}" -gt 0 ]; then
    set -x
fi
set -eu
set -o pipefail

[ -n "${ARCH}" ]
[ -n "${TARGET_ROOT}" ]

if [ 'amd64' = "${ARCH}" ] ; then
    ARCH='x86_64'
fi

if ! [ 'x86_64' = "${ARCH}" ] ; then
    echo "Only x86_64 images are currently available but ARCH is set to ${ARCH}."
    exit 1
fi

if [[ "${GENTOO_PROFILE}" != 'hardened/linux/musl/amd64' ]]; then
    echo 'not a musl profile'
    exit 1
fi

BASE_IMAGE_FILE="http://distfiles.gentoo.org/experimental/amd64/musl/stage4-amd64-musl-hardened-20171101.tar.bz2"
BASE_IMAGE_FILE="file:///var/tmp/catalyst/builds/musl/hardened/amd64/stage4-amd64-musl-hardened-20171031.tar.bz2"
CACHED_FILE="${DIB_IMAGE_CACHE}/gentoo-stage4-hardened-musl-20171101.tar.bz2"

if [ -n "${DIB_OFFLINE}" -a -f "${CACHED_FILE}" ] ; then
    echo "Not checking freshness of cached ${CACHED_FILE}"
else
    echo 'Fetching Base Image'
    "${TMP_HOOKS_PATH}"/bin/cache-url "${BASE_IMAGE_FILE}" "${CACHED_FILE}"
fi

# Extract the base image (use --numeric-owner to avoid UID/GID mismatch between
# image tarball and host OS)
sudo tar -C "${TARGET_ROOT}" --numeric-owner --xattrs -xjpf "${CACHED_FILE}"