#!/bin/bash

# Usage:
#     ./rename-tarball original-name.tar.gz new-name.tar.gz
#
# The generated new-name.tar.gz will always have a single main
# directory (named new-name to match the tarball name) in the archive.
# If the original tarball had multiple files in the main directory of
# the archive, all those files will be moved to under the new main
# directory.

set -euo pipefail
IFS=$'\n\t'

positional_args=()
while [[ "$#" -gt 0 ]]; do
    arg="${1}"
    case "${arg}" in
        -h|--help)
            print_usage
            exit 0
            ;;
        *)
            positional_args+=("$1")
            shift
            ;;
    esac
done

if [[ -z "${positional_args[0]:-}" ]]; then
    echo "error: missing original tarball name"
    exit 1
fi

original_path=$(readlink -f "${positional_args[0]:-}")
original_name=$(basename "$original_path")

new_name=${positional_args[1]:-}
if [[ -z ${new_name} ]]; then
    echo "error: missing new tarball name"
    exit 1
fi

original_name=${original_name/%.tar.gz}
new_name=${new_name/.tar.gz}

echo "Original: ${original_name}.tar.gz"
echo "New name: ${new_name}.tar.gz"

mkdir "temp-${new_name}"
pushd "temp-${new_name}" > /dev/null
tar xf "${original_path}"
# `find` always shows the current directory as one of the entries in
# the output. A total of 2 entries means there is only one main
# directory in the extracted archive, and we can just move it to the
# expected location.
if [[ $(find . -maxdepth 1 | wc -l) == 2 ]]; then
    mv -- ./* ../"${new_name}"
else
    mkdir -p ../"${new_name}"
    mv -- ./* ../"${new_name}"
fi
popd > /dev/null
tar czf "${new_name}.tar.gz" "${new_name}"
rm -rf "${new_name}"
rmdir "temp-${new_name}"