#!/bin/bash export PATH="$PATH:/sbin:/usr/sbin" usage () { echo -e "Usage:\t$0 -c -i -d [ -s ] [ -f ] [ -t ] [ -u ]" echo -e "\t\t-e -i -d [ -b ] [ -u ]" exit 1 } create_disk_img () { local datadir=$1 local imgfile=$2 local imgsize=$3 local fstype=$4 local imgtype=$5 [ -z "$imgsize" ] && imgsize="100G" [ -n "$fstype" -a "$fstype" != "vfat" ] && \ echo -e "WARNING: Only VFAT images are supported by Rainbow essentials.\n"\ " Enable libguestfs support for ${fstype}.\n"\ " Forcing VFAT file system type." # Create qcow2 image: qemu-img create -f qcow2 -o cluster_size=2M,preallocation=metadata $image 100G # To mount qcow2 image qemu-nbd is needed, but Qemu in RHEL6 is missing support of this feature # So Rainbow basic image operations method will support RAW images only [ -n "$imgtype" -a "$imgtype" != "raw" ] && \ echo -e "WARNING: Only RAW images are supported by Rainbow essentials. \n"\ " Enable libguestfs support for ${imgtype}.\n"\ " Forcing RAW image format.\n" imgtype="raw" fstype="vfat" qemu-img create -f $imgtype $imgfile $imgsize # windows wants the partition on disk parted -s $imgfile mklabel msdos parted -a opt -s -- $imgfile mkpart primary fat32 0 -0 part_offset=$( parted -s $imgfile unit B print | sed -n 's/\s*1\s*\([0-9]\+\)B\s*[0-9]\+B.*/\1/p' ) # # this part requeres root proveledges # loopdev=$( losetup -f --show -o $part_offset $imgfile ) if [ "$fstype" = "vfat" ]; then # TODO: ext3 support? mkdosfs -F32 -n DATA $loopdev fi mountpoint="${datadir}-img" mkdir -p $mountpoint mount -t vfat $loopdev $mountpoint cp -r ${datadir}/* $mountpoint umount $loopdev rmdir $mountpoint losetup -d $loopdev } extract_disk_img () { local imgfile=$1 local datadir=$2 local basepath=$3 part_offset=$( parted -s $imgfile unit B print | sed -n 's/\s*1\s*\([0-9]\+\)B\s*[0-9]\+B.*/\1/p' ) loopdev=$( losetup -f --show -o $part_offset $imgfile ) mountpoint="${datadir}-img" mkdir -p $mountpoint mkdir -p $datadir mount $loopdev $mountpoint ls ${mountpoint}/${basepath} >/dev/null 2>&1 [ $? -eq 0 ] && cp -r ${mountpoint}/${basepath}/* $datadir || echo "Base path does not exist. Extraction failed." umount $loopdev rmdir $mountpoint losetup -d $loopdev } [ $# -eq 0 ] && usage # parse options while getopts ":cei:d:s:f:t:u:b:" opt; do case $opt in c) createimg=1 ;; e) extractimg=1 ;; i) imgfile="$OPTARG" ;; d) datadir="$OPTARG" ;; s) imgsize="$OPTARG" ;; f) fstype="$OPTARG" ;; t) imgtype="$OPTARG" ;; u) owner="$OPTARG" ;; b) basepath="$OPTARG" ;; \?) usage ;; :) echo "Option -$OPTARG requires an argument." >&2 usage ;; esac done if [ -n "$createimg" ]; then [ -n "$extractimg" ] && usage [ ! -d "$datadir" ] && usage [ -z "$imgfile" ] && usage exec 1>&2 create_disk_img "$datadir" "$imgfile" $imgsize $fstype $imgtype [ -n "$owner" ] && chown "$owner" "$imgfile" elif [ -n "$extractimg" ]; then [ ! -f "$imgfile" ] && usage [ -z "$datadir" ] && usage exec 1>&2 extract_disk_img "$imgfile" "$datadir" "$basepath" [ -n "$owner" ] && chown -R "$owner" "$datadir" else usage fi