#!/bin/bash
#
# Initial script for Live operating system
# This script are launching before starting init from linux-live 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='.'; CMD_CHROOT='chroot . '; }
SOURCE=${ROOTFS}/usr/lib/ublinux/functions; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null || exit 0
SOURCE=${ROOTFS}/usr/lib/ublinux/os-config; [[ -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_qemu_path(){
    STORAGE_QEMU_POOL_NAME="storage.qemu"
    STORAGE_QEMU_PATH_DEFAULT="/memory/layer-base/1/storage.qemu"
    if [[ -n ${STORAGE_QEMU_PATH} ]]; then
	if [[ ${STORAGE_QEMU_PATH,,} == @(y|yes|enable) ]]; then
	    STORAGE_QEMU_PATH=${STORAGE_QEMU_PATH_DEFAULT}
	fi
	[[ -d ${ROOTFS}/etc/libvirt/storage/autostart ]] || install -dm0755 ${ROOTFS}/etc/libvirt/storage/autostart
	[[ -d ${ROOTFS}/${STORAGE_QEMU_PATH} ]] || install -dm0755 ${ROOTFS}/${STORAGE_QEMU_PATH}
	if [[ -d ${ROOTFS}/${STORAGE_QEMU_PATH} ]]; then
	    ln -sf /etc/libvirt/storage/${STORAGE_QEMU_POOL_NAME}.xml ${ROOTFS}/etc/libvirt/storage/autostart/${STORAGE_QEMU_POOL_NAME}.xml
	    cat <<EOF > "${ROOTFS}/etc/libvirt/storage/${STORAGE_QEMU_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_QEMU_POOL_NAME}
or other application using the libvirt API.
-->

<pool type='dir'>
  <name>${STORAGE_QEMU_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_QEMU_PATH}</path>
  </target>
</pool>
EOF
	fi
	
    fi
}

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

    exec_storage_qemu_path $@
