# Default shell library for eimg utils.
# Copyright (C) 2015 Red Hat, Inc.
# Written by Pavel Raiskup.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

: "${eimg_virt_name=eimg-img-prep}"
: "${LIBVIRT_DEFAULT_URI=qemu:///system}"
export LIBVIRT_DEFAULT_URI

eimg_info ()
{
    echo >&2 " * $*"
}

eimg_error ()
{
    echo >&2 " ! $*"
}

eimg_die ()
{
    eimg_error "$*"
    exit 1
}

eimg_generate_passwd ()
{
    eimg_generate_passwd_result=`openssl passwd -1 "$1"`
    test -z "$eimg_generate_passwd_result" && die "can't generate passwd"
}

eimg_remote_run ()
{
    local cmd="$1"
    echo "running: $cmd"
    ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes "root@$eimg_ip" "$cmd"
}

eimg_load_ip ()
{
    eimg_ip=$( /usr/libexec/eimg-get-ipv4 "$eimg_virt_name" )
    case $eimg_ip in
    "") eimg_die "IP not found" ;;
    *.*.*.*) eimg_info "IP address is $eimg_ip" ;;
    *) eimg_die "$eimg_ip is not IPv4" ;;
    esac
}

eimg_wait_for_ip ()
{
    until eimg_ip=$( /usr/libexec/eimg-get-ipv4 "$eimg_virt_name" ); do
        sleep 3
    done
    if ${EIMG_DOUBLECHECK_WAITING_FOR_IPV4-false}; then
        sleep 30
        eimg_ip=$( /usr/libexec/eimg-get-ipv4 "$eimg_virt_name" )
    fi
}

eimg_guess_pkg_manager ()
{
    eimg_pkg_manager=$(ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes "root@$eimg_ip" 'if test -e /usr/bin/dnf  &>/dev/null; then echo dnf; elif rpm -q microdnf &>/dev/null; then echo microdnf; else echo yum; fi')
    eimg_info "Guessed package manager: $eimg_pkg_manager"
}

eimg_download_image ()
{
  _tmpdir=/tmp
  _orig_image=$1
  eimg_download_image_result=$_tmpdir/$(basename "$_orig_image")
  if test -f "$eimg_download_image_result"; then
      echo "using pre-downloaded image $eimg_download_image_result"
  else
      echo "Going to download $_orig_image into $eimg_download_image_result"
      curl -L -f "$_orig_image" > "$eimg_download_image_result" || {
          echo "can not download"
          rm -rf "$eimg_download_image_result"
          exit 1
      }
  fi
}
