#!/usr/bin/bash -x

. "/etc/eimg/eimg.sh"
. "/usr/share/eimg"/lib
: ${EIMG_PLAYBOOK=local-image-update.yml}
: ${EIMG_PLAYBOOK_DIR=/tmp}
: ${EIMG_ANSIBLE_IN_CONTAINER=false}

eimg_load_ip

cd "$EIMG_PLAYBOOK_DIR" || exit 1

# Sometimes the IPA in Red Hat Copr deployment slows the initial connection
# down.
export ANSIBLE_TIMEOUT=200
export ANSIBLE_HOST_KEY_CHECKING=False

cmd=( ansible-playbook -i "$eimg_ip," "$EIMG_PLAYBOOK" "${EIMG_PLAYBOOK_ARGS[@]}" )

if $EIMG_ANSIBLE_IN_CONTAINER; then
  while ! podman run --rm -ti --privileged \
    -e ANSIBLE_HOST_KEY_CHECKING \
    -e ANSIBLE_TIMEOUT \
    -v "$EIMG_PLAYBOOK_DIR:$EIMG_PLAYBOOK_DIR:z" \
    -v "$HOME/.ssh:$HOME/.ssh:z" \
    ansible \
  "${cmd[@]}" ; do
    cat <<EOF
Playbook failed.  Retrying.  Known things you might need to do async:
- systemctl start user@11666
- chown copr:copr -R /home/copr/provision
EOF
    sleep 10
  done
else
  "${cmd[@]}"
fi
