#!/bin/bash
set -e

# make basic arguments for cre
if [[ $CONTAINER ]]; then
    name=$CONTAINER
else
    if [[ $PKGNAME ]]; then
        pkgname=$PKGNAME
    else
        source PKGBUILD
        pkgname=$(echo "$pkgname" | tr '+' 'p')
    fi
    uuid=$(cat /proc/sys/kernel/random/uuid)
    name=makechrootpkg-$pkgname-$uuid
fi
cre_args=(--name "$name" --workdir "/startdir" -v "$PWD":/startdir -it)

# parse arguments
script_args= read_script_args= no_sync=
for arg in "$@"; do
    if [[ $read_script_args ]]; then
        if [[ $arg == '--nodeps' ]] || [[ $arg == '-d' ]]; then
            no_sync=1
        fi
        script_args+=" '$arg'"
    else
        if [[ $arg == '--' ]]; then
            read_script_args=1
        else
            cre_args+=("$arg")
        fi
    fi
done

# add arguments from environment
if [[ $PACMAN_PKG_CACHE_DIR ]]; then
    cre_args+=(-v "$PACMAN_PKG_CACHE_DIR":/var/cache/pacman/pkg)
fi
if [[ $CONTAINER_BUILD_CFG_DIR ]]; then
    cre_args+=(-v "$CONTAINER_BUILD_CFG_DIR":/cfg)
fi
if [[ $CONTAINER_BUILD_CCACHE_DIR ]]; then
    cre_args+=(-v "$CONTAINER_BUILD_CCACHE_DIR":/ccache)
    script_args+=' CCACHE_DIR=/ccache'
fi

# load "containerbuild" and "containersync" script
bindir=$(dirname "$0")
script=$(cat "$bindir/containerbuild")
if ! [[ $no_sync ]]; then
    script_sync=$(cat "$bindir/containersync")
fi

# invoke containerized build
ec=0 cre=${CRE:-docker}
if ! [[ $CONTAINER ]]; then
    "$cre" container create "${cre_args[@]}" "${CRE_IMAGE:-archlinux-base-devel}"
    "$cre" container start "$name"
fi
"$cre" container exec "$name" bash \
    -c "$script_sync $script $script_args" || ec=$?

# stop and remove container unless we want to keep it for debugging
[[ $ec == 0 && $DEBUG == on-failure || -z $DEBUG ]] && \
    "$cre" container rm --force --time 0 "$name"

# log message about commands to use for investigation
[[ $ec != 0 ]] && [[ $DEBUG ]] && echo \
    "You may investigate the failure via:
    $cre exec -it '$name' bash
    $cre mount '$name'
You may retry the build using the same container again via:
    CONTAINER='$name' DEBUG='$DEBUG' $0 $@"

exit $ec
