#!/bin/bash
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-

prog=`basename $0 .bash`
PREFIX=/usr/local

[ -f /usr/local/bin/usr_local_tput.bash ] && \
    . /usr/local/bin/usr_local_tput.bash || {
	DBUG() { echo DEBUG $* ; }
	INFO() { echo INFO $* ; }
	WARN() { echo WARN $* ; }
	ERROR() { echo ERROR $* ; }
    }

ROLE=toxcore
BOX=gentoo1
EXE=python3.sh

export PLAY_ANSIBLE_SRC=/o/var/local/src/play_tox
yamllint -c $PLAY_ANSIBLE_SRC/.yamllint.rc $PLAY_ANSIBLE_SRC/hosts.yml || {
    ERROR
    exit 1
}
[ "$#" -eq 0 ] && set -- build

# put these values in $BASE_SRC_ANSIBLE/hosts.yml

[ -n "$BOX_NBD_FILES" ] || \
  BOX_NBD_FILES=$( /usr/local/bin/ansible_get_inventory.bash BOX_NBD_FILES $BOX)
[ -n "$BOX_NBD_BASE_QCOW" ] || \
    BOX_NBD_BASE_QCOW=$( /usr/local/bin/ansible_get_inventory.bash BOX_NBD_BASE_QCOW $BOX)
[ -n "$BOX_NBD_LOGLEVEL" ] || \
    BOX_NBD_LOGLEVEL=$( /usr/local/bin/ansible_get_inventory.bash BOX_NBD_LOGLEVEL $BOX)
[ -z "$BOX_NBD_LOGLEVEL" ] && BOX_NBD_LOGLEVEL=20
DBUG "BOX_NBD_LOGLEVEL=$BOX_NBD_LOGLEVEL"

declare -a RARGS
RARGS=(-j 1)
if [ -n "$BOX_NBD_FILES" ] && [ -d "$BOX_NBD_FILES" ] ; then
    PORTAGE="$BOX_NBD_FILES"/portage-20231223.tar.xz
    [ -f $PORTAGE ] && RARGS+=(--portage $PORTAGE)
    STAGE3="$BOX_NBD_FILES"/stage3-amd64-openrc-20231217T170203Z.tar.xz
    [ -f $STAGE3 ] && RARGS+=(--stage3 $STAGE3)
    RARGS+=( --download-dir $BOX_NBD_FILES )
fi
[ -n "$BOX_NBD_BASE_QCOW" ] && \
    BOX_NBD_BASE_DIR=$(dirname  "$BOX_NBD_BASE_QCOW") && \
    [ -d  "$BOX_NBD_BASE_DIR" ] && \
    RARGS+=( --temporary-dir "$BOX_NBD_BASE_DIR" )

export BOX_NBD_OVERLAY_DIR
LOGLEVEL=20

JSON=$PLAY_ANSIBLE_SRC/src/ansible_gentooimgr/gentooimgr/configs/base.json
if [ -n "$JSON" ] && [ -f "$JSON" ] ; then
    PKGS=`yq .packages.base < $JSON`
    DBUG gentooimgr "${PKGS}"
    RARGS+=( --config "$JSON" )
fi

# default --kernel-dir /usr/src/linux
RARGS+=( --config-base --loglevel $LOGLEVEL --days 27 --openrc --format qcow2 )

DBUG  gentooimgr "${RARGS[@]}" "$@"
PYTHONPATH=$PLAY_ANSIBLE_SRC/src/ansible_gentooimgr $EXE \
	  -m gentooimgr \
	  "${RARGS[@]}" "$@"
retval=$?
[ $retval -gt 0 ] && exit 1$retval

#[ -f $BOX_NBD_OVERLAY_DIR/images/$BOX_NBD_OVERLAY_NAME.img ] && \
#    INFO $BOX_NBD_OVERLAY_DIR/images/$BOX_NBD_OVERLAY_NAME.img || {
#    ERROR NO $BOX_NBD_OVERLAY_DIR/images/$BOX_NBD_OVERLAY_NAME.img  ; exit 2$retval ; }
exit 0

