#!/usr/bin/env bash

# This small helper file allow you to create, make content and play
# with sparse file
# Part of Bareos Training by Ioda-Net Sàrl
#

BASE="`pwd`"

if [ $UID -ne 0 ];then
  echo "sorry need to be run as root"
  return 1
fi

# Script to create sparse file example with a bit of contain in it
F="/data/samples/sparse_file.img"
M="/tmp/tmpSPARSE"
if [ ! -d ${M} ];then
  mkdir ${M}
fi

function sparse_report_size {
  du -h --apparent-size ${F}
  du -h ${F}
  if [ $(mount | grep ${M} | wc -l) -eq 1 ]; then
    df -h ${M}
  fi
}

function sparse_cleanup {
  _sparse_umount
  rm -fr ${M}
  rm -f ${F}
}

function sparse_create_512 {
  sparse_cleanup
  mkdir ${M}
  truncate -s 512M ${F}
  mkfs.ext4 -L SPARSE_TEST -m 5 ${F}
}


function sparse_resize_1G {
  dd if=/dev/zero of=${F} bs=1 count=0 seek=1G
  e2fsck -f ${F}
  resize2fs -p ${F}
  sparse_report_size
}

function sparse_resize_4G {
  dd if=/dev/zero of=${F} bs=1 count=0 seek=4G
  e2fsck -f ${F}
  resize2fs -p ${F}
  sparse_report_size
}


function _sparse_mount {
  mount -o loop ${F} ${M}
  if [ $? -ne 0 ];then
    echo "Error during mount loop"
    return 1
  fi

  chown admin:users -R ${M}
  cd ${M}

}

function _sparse_umount {
  cd ${BASE}
  if [ -f ${F} ];then
    if [ $(mount | grep ${M} | wc -l) -eq 1 ]; then
      umount ${F}
      if [ $? -ne 0 ];then
        echo "Error during umount loop"
        lsof ${F}
        return 1
      fi
    fi
  fi
}

function sparse_create_content {
  _sparse_mount
  mkdir folder
  for f in {1..5}; do touch folder/file${f}; done
  echo "This is a test to see if it works..." >> folder/file1
  dd if=/dev/urandom of=folder/random4M.dat bs=4k count=1000
  sync
  ls -Rlh ${M}/*
  _sparse_umount
  sparse_report_size
}

function sparse_create_content_more {
  _sparse_mount
  mkdir resized
  for f in {1..5}; do touch resized/file${f}; done
  echo "This is a test to see if resized works..." >> resized/file1
  dd if=/dev/urandom of=resized/random41M.dat bs=4k count=10000
  sync
  ls -Rlh ${M}/*
  _sparse_umount
  sparse_report_size
}

function sparse_create_content_ultimate {
  _sparse_mount
  mkdir resized
  for f in {10..50}; do echo "$f" > resized/file${f}; done
  echo "This is a test to see if resized works..." >> resized/file1
  dd if=/dev/urandom of=resized/random410M.dat bs=4k count=100000
  sync

  ls -Rlh ${M}/*
  _sparse_umount
  sparse_report_size
}


echo "usage : source $0"
echo "Available functions : sparse_create_512 sparse_create_content sparse_resize_1G sparse_resize_4G sparse_create_content_more sparse_create_content_ultimate sparse_report_size (sparse_cleanup)"
