#!/bin/bash

SCRIPT_NAME=$(basename "$0")
SCRIPT_DIR=$(dirname "$0")
BASE_DIR="$SCRIPT_DIR/.."
BASE_DIR=$(realpath "$BASE_DIR")
HELPERS_DIR="$BASE_DIR/helpers"
ARTIFACTS_DIR="$BASE_DIR/artifacts"
UPLOAD_PACKAGE_TO_S3="0"
UPLOAD_LATEST_STABLE_TO_S3="0"

ARCHIVE_BUILD_DIR="builds"
VERSION_FILENAME=".version"


# Print usage info and exit
usage()
{
  echo
  echo "About:"
  echo "  Packages vperfcheck into a .tar.gz archive."
  echo
  echo "Usage:"
  echo "  $ $SCRIPT_NAME [options]"
  echo
  echo "Optional Arguments:"
  echo "  -s  Upload release package to S3 as latest stable release. Only effective in"
  echo "      in combination with '-U'."
  echo "  -U  Upload release package to S3. Requires environment variables"
  echo "      AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to be set."
  echo
  echo "Examples:"
  echo " Build local package and upload as new latest stable:"
  echo " $ AWS_ACCESS_KEY_ID=AKI... AWS_SECRET_ACCESS_KEY=\"...\" $SCRIPT_NAME -U -s"
  echo

  exit 1
}

# Parse command line arguments
parse_args()
{
  local OPTIND # local to prevent effects from other subscripts

  while getopts "ehsU" opt; do
    case "${opt}" in
      h)
        # help
        usage
        ;;
      s)
        # upload as latest stable to s3
        UPLOAD_LATEST_STABLE_TO_S3="1"
        ;;
      U)
        # upload package to s3
        UPLOAD_PACKAGE_TO_S3="1"
        ;;
      *)
        # Other option arguments are invalid
        echo "ERROR: Invalid argument: ${OPTARG}" >&2
        echo
        usage
        ;;
    esac
  done
}

# Confirm that we are in the root directory of the git repo checkout.
check_repo_root_dir()
{
  local check_filename="vperfcheck.sh"
  
  if [ ! -e "$check_filename" ]; then
    echo "ERROR: Important file not found in current directory." \
      "Are you not calling this from the root directory of a git checkout?" \
      "Missing file: $check_filename" >&2
    exit 1
  fi
}

# upload given package file to s3. access key and secret are assumed to be set via environment
# variables AWS_ACCESS_KEY_ID & AWS_SECRET_ACCESS_KEY.
#
# $1: path to package file to upload
upload_package_to_s3()
{
  local package_path_local="$1"
  local package_filename_local="$(basename "$package_path_local")"
  local stable_filename_s3="vperfcheck-latest-stable.tar.gz"

  local package_path_s3="s3://vast-vperfsanity/download/$package_filename_local"
  local http_download_path="http://vast-vperfsanity.s3.amazonaws.com/download/$package_filename_local"

  local stable_path_s3="s3://vast-vperfsanity/download/$stable_filename_s3"
  local http_stable_download_path="http://vast-vperfsanity.s3.amazonaws.com/download/$stable_filename_s3"

  echo "Uploading package to S3: $package_path_s3"
  aws s3 cp "$package_path_local" "$package_path_s3"

  if [ $? -ne 0 ]; then
    echo "ERROR: Upload to S3 failed." >&2
    exit 1
  fi

  echo "Upload succeeded. Package available here: $http_download_path"

  if [ "$UPLOAD_LATEST_STABLE_TO_S3" -eq 0 ]; then
    return
  fi

  echo "Uploading latest stable package to S3: $stable_path_s3"
  aws s3 cp "$package_path_local" "$stable_path_s3"

  if [ $? -ne 0 ]; then
    echo "ERROR: Upload latest stable to S3 failed." >&2
    exit 1
  fi

  echo "Upload succeeded. Package available here: $http_stable_download_path"
}

########################### END OF FUNCTION DEFINITIONS ############################

parse_args "$@"

if [ "$(pwd)" != "$BASE_DIR" ]; then
    echo "Changing into base directory: $BASE_DIR"
    cd "$BASE_DIR"
fi

# make sure we are in the right directory
check_repo_root_dir

# version is the short git hash + date
VERSION=$(git log --format=%as-%h -n 1 HEAD 2>/dev/null)

if [ $? -ne 0 ]; then
    VERSION="$(date +%Y%m%d%H%M%S)nogit"
    echo "[INFO] Unable to get version from git log. Using date-based version."
fi

# archive filename includes version string
ARCHIVE_FILENAME="vperfcheck-$VERSION.tar.gz"

# make sure the build directory exists
mkdir -p "$ARCHIVE_BUILD_DIR"

# if the build is there already for some reason, delete it
if [ -f "$ARCHIVE_BUILD_DIR/$ARCHIVE_FILENAME" ]; then
    echo "[INFO] Removing existing build for this release: $ARCHIVE_BUILD_DIR/$ARCHIVE_FILENAME"
    rm -f "$ARCHIVE_BUILD_DIR/$ARCHIVE_FILENAME"
fi

# create a text file containing the version
echo $VERSION > "$VERSION_FILENAME"

# tar up the contents
# (note: this transforms "." into the dir name "vperfcheck")
# (note: we don't use "./" for transform regex search because it doesn't match the base dir, which
# must not be included as it would change the permissions of the current dir on extraction.)
if [ $(uname) = "Darwin" ]; then
    # (note: Mac OS tar has "-s" instead of "-transform")
    tar --exclude-vcs -s '!^\.!vperfcheck!' --exclude artifacts/elbencho \
        --exclude $ARCHIVE_BUILD_DIR -c -z -f "$ARCHIVE_BUILD_DIR/$ARCHIVE_FILENAME" .
else
    tar --exclude-vcs --exclude artifacts/elbencho --transform 's!^\.!vperfcheck!g' \
        --exclude $ARCHIVE_BUILD_DIR -c -z -f "$ARCHIVE_BUILD_DIR/$ARCHIVE_FILENAME" .
fi

if [ $? -ne 0 ]; then
    echo "ERROR: Archive creation failed." >&2
    exit 1
fi

# remove the version file
rm -f "$VERSION_FILENAME"

echo "Build available at: $BASE_DIR/$ARCHIVE_BUILD_DIR/$ARCHIVE_FILENAME"

# upload to s3
if [ "$UPLOAD_PACKAGE_TO_S3" -eq "1" ]; then
  upload_package_to_s3 "$ARCHIVE_BUILD_DIR/$ARCHIVE_FILENAME"
fi

echo
echo "All done."
