#!/usr/bin/env bash

set -xeuo pipefail

if [ "$#" -lt 2 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  cat <<USAGE
Usage: $0 result_package_name tarball-package-names...

Example: $0 yaml-cpp yaml-cpp.tar.gz
USAGE

  exit 1
fi

package_name="$1"
tarball_path="$(pwd)/$2"

# This converts absolute symlinks to symlinks relative to the current working
# directory.
function absolute_to_relative() {
  local link="$1"
  local to_root=""
  local root_dir
  local intermediate_dir

  if readlink "$link" | grep --quiet --extended-regexp '^/'; then
    root_dir="$(readlink --canonicalize "$(pwd)")"
    intermediate_dir="$(readlink --canonicalize "$(dirname "$link")")"
    while [ "$intermediate_dir" != "$root_dir" ]; do
      if [ "$intermediate_dir" == "/" ]; then
        echo Intermediate directory is invalid while searching for root! >&2
        exit 1
      fi
      to_root="../$to_root"
      intermediate_dir="$(dirname "$intermediate_dir")"
    done
    # Remove trailing '/' so we don't have '//' anywhere in the path.
    to_root="${to_root%/}"

    ln --symbolic --force "$to_root$(readlink "$link")" "$link"
  fi
}
export -f absolute_to_relative

temp_dir="$(mktemp --directory --tmpdir "$package_name".XXXXXXXXXX)"
(
  cd "$temp_dir"

  mkdir package
  (
    cd package
    tar -xzf "$tarball_path"

    find . -type l | xargs --max-args=1 bash -c 'absolute_to_relative "$@"' _
    tar -czf ../"$package_name".tar.gz ./
  )

  sha_256="$(sha256sum "$package_name.tar.gz" | awk '{print $1}')"

  cat <<MESSAGE
Tarball created!

Temp dir: $temp_dir
Tarball : $temp_dir/$package_name.tar.gz
Test dir: $temp_dir/package
sha256  : $sha_256

Test this repository out by adding this to the WORKSPACE file and adding an
appropriate build file:

\`\`\`
bind(
    name = "$package_name",
    actual = "@${package_name}_repo//:$package_name",
)

new_local_repository(
    name = "${package_name}_repo",
    path = "$temp_dir/package",
    build_file = "//build:$package_name.bazel",
)
\`\`\`

When that works as expected, upload the tarball to S3 like so:

If you have not done so already, you may need to run `bazel run //scripts/build:init_z3_profile`.

\`\`\`
aws --endpoint-url=https://z3.zooxlabs.com --profile=z3 s3 cp $temp_dir/$package_name.tar.gz s3://zoox-third-party/$sha_256/$package_name.tar.gz \\
    --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers
\`\`\`

And modify the WORKSPACE file to:

\`\`\`
bind(
    name = "$package_name",
    actual = "@${package_name}_repo//:$package_name",
)

new_http_archive(
    name = "${package_name}_repo",
    url = "https://z3.zooxlabs.com/zoox-third-party/$sha_256/$package_name.tar.gz",
    sha256 = "$sha_256",
    build_file = "//build:$package_name.bazel",
)
\`\`\`
MESSAGE
)
