#!/usr/bin/env bash

set -e
set -u
set -o pipefail

esyCommandHelp() {
  cat <<EOF
usage: esy export-build <build-id>

This command exports the build specified by the <build-id> from global
store into \$PWD/_export/<build-id>.tar.gz archive.

This build can be imported by the 'esy import-build' command.

EOF
}

BINDIR=$(dirname "$0")

# shellcheck source=./realpath.sh
source "$BINDIR/realpath.sh"
# shellcheck source=./esyConfig.sh
source "$BINDIR/esyConfig.sh"
# shellcheck source=./esyRuntime.sh
source "$BINDIR/esyRuntime.sh"

buildPath="$1"
buildId=$(basename "$buildPath")

stageDir=$(mktemp -d)
stageBuildPath="$stageDir/$buildId"

outputDir="$PWD/_export"
outputPath="$outputDir/$buildId.tar.gz"

function _do () {
  set -e
  set -u
  set -o pipefail

  local origStorePath
  local destStorePath

  # copy into stage recursively (-R) and do not follow symlinks (-P)
  cp -RP "$buildPath" "$stageBuildPath"

  origStorePath=$(cat "$stageBuildPath/_esy/storePrefix")
  destStorePath=${origStorePath//?/_}

  esyRewriteStorePrefix "$stageBuildPath" "$origStorePath" "$destStorePath"

  mkdir -p "$outputDir"
  rm -rf "$outputPath"

  (cd "$stageDir" && tar -czf "$outputPath" "$buildId")
}

echo "$buildId: exporting..."

set +e
(_do)
ret="$?"
set -e

rm -rf "$stageBuildPath"

if [ $ret -ne 0 ]; then
  exit 1
fi
echo "$buildId: done"
