# Calculate run=/bin/bash os_arch_machine==x86_64 ini(overlay-calculate.revision)<#-cut(0,-,#-cl_pass_file-#)-#

migrate_need_space() {
	/usr/local/sbin/unsymlink-lib --migrate -p 2>/dev/null | grep ^cp | sed 's/cp -a --reflink=auto --//' | xargs du -bsc 2>/dev/null | tail -1 | awk '{print $1}'
}

root_free_space() {
	echo "$(df / | tail -1 | awk '{print $4}')000"
}

not_numbers() {
	echo $* | grep -q "[^ 0-9]"
}

if [[ -d /lib.new ]]
then
	echo "Clearing previous failed migration"
	/usr/local/sbin/unsymlink-lib --force-rollback &>/dev/null
fi


echo "Analyzing files installed into lib & lib64"

if /usr/local/sbin/unsymlink-lib --analyze &>/dev/null
then
	echo "Calculating necessary space for migration"
	needspace="$(migrate_need_space)"
	freespace="$(root_free_space)"
	if not_numbers "$needspace" "$freespace"
	then
		echo "Failed to calculate migrate need space" 1>&2
	else
		if [[ "$(( $needspace + 100000000 ))" -gt "$freespace" ]]
		then
			echo "Not enough space for migration" 1>&2
		else
			echo "Performing unsymlink lib migration"
			if /usr/local/sbin/unsymlink-lib --migrate &>/dev/null
			then
				if /usr/local/sbin/unsymlink-lib --finish &>/dev/null
				then
					echo "Migration completed successfully"
					exit 0
				else
					echo "Failed to finish migration" 1>&2
				fi
			else
				echo "Failed to perform migration" 1>&2
				/usr/local/sbin/unsymlink-lib --force-rollback &>/dev/null
			fi
		fi
	fi
	exit 1
else
	echo "Failed to perform unsymlink lib analyze" 1>&2
	exit 1
fi
