#!/bin/bash
# This script is to mount\unmount .iso OS images assigned to the current DP and delivered via dpservice 

function Write_Log {
	message=$1
	severity=$2

	if [[ $severity == "" ]]; then severity="INFO"; fi
	timestamp=$(date --iso-8601=ns | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
	log_line="[$timestamp][${severity^^}]: $message"
	echo "$log_line" | tee -a "$log_file_path"
}

#.imrpt file content:
#ImageId=0
#ExitCode=<status>
#StdErr=<some error if exists>
#StdOut=<some useful information>
function Report_Image {
	local imgid=$1 
	local status=$2
	local output=${3:-""}
	local error=${4:-""}
	
	printf "ImageId=$imgid\nExitCode=$status\nStdErr=$error\nStdOut=$output" > $reportfolder/$imgid.imrpt
}

function Mount_Image {
	local imgid=$1
	local filename=$2
	local res=0
	
	Write_Log "Checking image ID $imgid, file $filename."
	
	ismounted=$(mount | grep "osimages/$imgid" | awk '{print $1}')
	if [[ "$ismounted" == *"$filename"* ]]; then 
		Write_Log "Already mounted: $imgid $ismounted" 
		Report_Image $imgid $status_success "Successfully mounted"
	else
		Write_Log "Image not mounted, mounting: $imgid $filename"
		Report_Image $imgid $status_inprogress "Mounting started"
		if [ ! -d "$mntpoint/$imgid" ]; then 
			mkdir -p $mntpoint/$imgid
			chmod o+r,g+r $mntpoint/$imgid
		fi
		mount -o loop "$storefolder/$filename" "$mntpoint/$imgid"
		res=$?
		if [[ $res -eq 0 ]]; then	
			Write_Log "Successfully mounted: $imgid $ismounted"
			Report_Image $imgid $status_success "Successfully mounted"
		else
			msg="Error $res when mounting. "
			if [ ! -e "/sys/module/loop" ]; then msg+="Check kernel loop module on DP. "; fi
			if [ ! -f "$storefolder/$filename" ]; then msg+="File $storefolder/$filename not found. "; fi
			Write_Log "$msg" "ERROR"
			Report_Image $imgid $status_failed  "$msg" "$res"
		fi
	fi
}

function Umount_Image {
	local imgid=$1
	local filename=$2
	
	dir=$mntpoint/$imgid
	ismounted=$(mount | grep "$dir" | awk '{print $1}')
	if [[ "$ismounted" == *"$filename"* ]]; then 
		Write_Log "Unmounting image ID $imgid"
		umount -f $dir
		res=$?
		if [[ $res -eq 0 ]]; then	
			Write_Log "Successfully unmounted image ID $imgid"
			rm -d $dir
			rm -f "$storefolder/$filename"
			rm -f "$imagesfolder/$imgid.immnt"
			rm -f "$reportfolder/$imgid.imrpt"
		else
			Write_Log "Error '$res' unmounting image ID $imgid" "ERROR"
			Report_Image $imgid $status_failed $res $msg
		fi
	else
		Write_Log "Can not unmount image ID $imgid, file $filename is not mounted" "ERROR"
	fi		
}

#### Initializing variables

script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
log_file_path="/var/log/colibri/automount.log"

#Exit codes
status_success=0
status_inprogress=1
status_failed=2

imagesfolder="$script_dir/img"
reportfolder="$script_dir/report"
storefolder="/opt/colibri/repositories/os/img_repo" 
mntpoint="/opt/colibri/repositories/osimages"


Write_Log "####### Automount start #######"


if [ ! -e "/sys/module/loop" ]; then
   Write_Log "Kernel loop module is not loaded! Trying to load..."  "ERROR"
   modprobe loop
fi

#.immnt file content
#id=0
#filename=image0.iso
#action=mount

for immntfile in $imagesfolder/*.immnt; do
	while IFS="=" read -r key value; do
		case "$key" in
			"id") 		id="$value" ;;
			"filename") filename="$value" ;;
			"action") 	action="$value" ;;
		esac
	done < "$immntfile"
	Write_Log "Detected image with id=[$id] filename=[$filename] action=[$action]"
	case "$action" in
		"mount")	Mount_Image "$id" "$filename";;
		"umount") 	Umount_Image "$id" "$filename";;
	esac
done

Write_Log "------- Automount stop -------"
