#!/bin/bash -eu

#
# Assumptions for this to work:
# [1] This script is executed from the root of the SDB repo
# [2] The archive downloaded from S3 has one of the following profiles:
#     Profile A - It is lzma-compressed and has the following file structure:
#           dump-data
#           ├── dump.201912060006
#           ├── mods
#           │   ├── avl
#           │   │   └── zavl.ko
#           .....
#           │   └── zfs
#           │       └── zfs.ko
#           └── vmlinux-5.0.0-36-generic
#     Profile B - It is gzip-compressed and generated by the savedump utility.
#
# Note: Profile A is deprecated. It was format used for dump archives created
#       manually.
#

DATA_DIR="tests/integration/data"

if [ $# -eq 0 ]; then
	echo "error: no crash dump archive argument supplied"
	exit 1
fi

echo "checking folder structure ..."
if [ ! -d $DATA_DIR ]; then
	echo "error: please cd to the root of the git repo"
	exit 1
fi

if [ -f "$1" ]; then
	echo "Found $1 locally, skip download ..."
else
	echo "downloading of $1 from S3 ..."
	wget https://sdb-testing-bucket.s3.us-west-2.amazonaws.com/$1
	[ $? -eq 0 ] || exit 1
fi

if [[ $1 == *.tar.lzma ]]; then
	# Profile A
	dump_name=${1%.tar.lzma}

	echo "decompressing dump ..."
	tar -x --lzma -f $1

	echo "moving contents to tests/integration/data/dumps/${dump_name} ..."
	mkdir -p $DATA_DIR/dumps/${dump_name}
	mv dump-data/* $DATA_DIR/dumps/${dump_name}
	[ $? -eq 0 ] || exit 1

	rmdir dump-data
	[ $? -eq 0 ] || exit 1
elif [[ $1 == *.tar.gz ]]; then
	# Profile B
	dump_name=${1%.tar.gz}

	echo "decompressing dump ..."
	tar xzf $1

	echo "moving contents to tests/integration/data/dumps/${dump_name} ..."
	mkdir -p $DATA_DIR/dumps/${dump_name}
	mv *${dump_name}/* $DATA_DIR/dumps/${dump_name}
	[ $? -eq 0 ] || exit 1

	rmdir *${dump_name}
	[ $? -eq 0 ] || exit 1
else
	echo "unknown dump profile"
	exit 1
fi

echo "Done"
