#!/usr/bin/env bash

set -e

HELP="usage: concat-bz2.sh -i=base-folder"

if [ "$1" == "" ]; then echo $HELP; exit 1; fi

BASEFODER=""

for i in "$@"
do
case $i in
    -i=*|--base-folder=*)
    BASEFODER="${i#*=}"
    shift # past argument=value
    ;;
    *)
    echo "unkown option $i"
    echo $HELP
    exit 1
    ;;
esac
done

for folder in $(find $BASEFODER -regex ".*bz2$" -type d)
do
  tmp_file=$(mktemp)
  echo "concat $folder/*.bz2 > $tmp_file > $folder"
  cat $(find $folder -regex ".*bz2$" -type f) > "$tmp_file"
  mv "$folder" "$folder.old"
  mv "$tmp_file" "$folder"
  rm -rf "$folder.old"
done

