#!/usr/bin/env bash
#
# Initial script for UBLinux
# This script are launching before starting init from initrd script
# Current dir allways must be set to root (/)
# All system path must be relative, except initrd dirs

ENABLED=yes
[[ ${ENABLED} == "yes" ]] || exit 0
DEBUGMODE=no

PATH=.:/:/usr/bin:/usr/local/bin:/usr/local/sbin

[[ -d /usr/lib/ublinux ]] && { unset ROOTFS; unset CMD_CHROOT; } || { ROOTFS="/sysroot"; CMD_CHROOT="chroot ${ROOTFS} "; }
SOURCE=${ROOTFS}/usr/lib/ublinux/functions; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null || exit 0
SOURCE=${ROOTFS}/usr/lib/ublinux/default; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null || exit 0
debug_mode "$0" "$@"

SYSCONF="${ROOTFS}${SYSCONF}"
SOURCE=${SYSCONF}/config; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null
SOURCE=${SYSCONF}/system; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null
SOURCE=${SYSCONF}/server; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null

exec_storage_libvirt_path(){
    STORAGE_LIBVIRT_POOL_NAME="storage.libvirt"
    STORAGE_LIBVIRT_PATH_DEFAULT="/memory/layer-base/1/${STORAGE_LIBVIRT_POOL_NAME}"
    if [[ -n ${STORAGE_LIBVIRT_PATH} ]]; then
	if [[ ${STORAGE_LIBVIRT_PATH,,} == @(y|yes|enable) ]]; then
	    STORAGE_LIBVIRT_PATH=${STORAGE_LIBVIRT_PATH_DEFAULT}
	    [[ -d ${STORAGE_LIBVIRT_PATH} ]] || install -dm0755 ${STORAGE_LIBVIRT_PATH}
	elif [[ ${STORAGE_LIBVIRT_PATH} =~ ^/memory/|^/mnt/(livemedia|livedata)/ ]]; then
	    [[ -d ${STORAGE_LIBVIRT_PATH} ]] || install -dm0755 ${STORAGE_LIBVIRT_PATH}
	fi
	cat <<EOF > "${ROOTFS}/etc/libvirt/storage/${STORAGE_LIBVIRT_POOL_NAME}.xml"
<!--
WARNING: THIS IS AN AUTO-GENERATED FILE. CHANGES TO IT ARE LIKELY TO BE
OVERWRITTEN AND LOST. Changes to this xml configuration should be made using:
  virsh pool-edit ${STORAGE_LIBVIRT_POOL_NAME}
or other application using the libvirt API.
-->

<pool type='dir'>
  <name>${STORAGE_LIBVIRT_POOL_NAME}</name>
  <uuid>22e1f043-1fcb-4017-8afd-d44ebea9c8e4</uuid>
  <capacity unit='bytes'>0</capacity>
  <allocation unit='bytes'>0</allocation>
  <available unit='bytes'>0</available>
  <source>
  </source>
  <target>
    <path>${STORAGE_LIBVIRT_PATH}</path>
  </target>
</pool>
EOF
    fi
    [[ -d ${ROOTFS}/etc/libvirt/storage/autostart ]] || install -dm0755 ${ROOTFS}/etc/libvirt/storage/autostart
    ln -sf /etc/libvirt/storage/${STORAGE_LIBVIRT_POOL_NAME}.xml ${ROOTFS}/etc/libvirt/storage/autostart/${STORAGE_LIBVIRT_POOL_NAME}.xml
}

################
##### MAIN #####
################

    exec_storage_libvirt_path $@
