#!/usr/bin/env bash

echo "Go go go..."
# setting path to directory with this script
CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" &&

if ! [[ "${FEATURE}" =~ ^[a-zA-Z0-9-]+$ ]]; then
    FEATURE="master"
fi &&

progress "Cleanup dist..." &&
if [ -d "${CURRENT_DIR}/../dist" ]; then rm -r "${CURRENT_DIR}/../dist"; fi &&

progress "Fetching configuration..." &&
if [ "${LOCAL}" == "true" ]; then LOCAL_PARAM="--local"; fi &&
get_config ${LOCAL_PARAM} --service content_builder --file "${CURRENT_DIR}/../env.json" &&

# init additional resources for deploy
# progress "Initializing Cloudfront..." &&
# init --resources-file ./resources.js &&

progress "Building Content Builder client..." && npm run build:service
# CLIENT=${CLIENT} ENV=${ENV} LOCAL=${LOCAL} npm run build &&

PACKAGE_VERSION=$(cat ./package.json | grep version | head -1 | awk -F= "{ print $2 }" | sed -E 's/(version)|[:,\",]//g' | tr -d '[[:space:]]')
# echo "PACKAGE_VERSION -> $PACKAGE_VERSION"

progress "Add version info..." &&
node ${CURRENT_DIR}/_add_version_info.js &&

if [ "${SYNC}" != "false" ]; then
    progress "Sync to s3..." &&
    SYNC_SOURCE="${CURRENT_DIR}/../dist" &&
    BUCKET="s3://content-assets.onereach.ai/apps/content-builder"
    # TARGET_VERSION="v/$PACKAGE_VERSION/"
    TARGET_VERSION="/$PACKAGE_VERSION/"
    # ORIGINAL_TARGET_WEB_UI="$(get_config --service sync.content_builder.target --type text)" &&
    ORIGINAL_TARGET="$(get_config --service sync.content_builder.target --type text)" &&
    TARGET_FOLDER="versions"
    # echo "target -> $ORIGINAL_TARGET_WEB_UI"
    # SYNC_TARGET="${ORIGINAL_TARGET/f\/master/$TARGET_FOLDER}$TARGET_VERSION"
    SYNC_TARGET="${BUCKET}${TARGET_VERSION}"
    # echo "replaced target -> $SYNC_TARGET"
    echo "Uploading Content Builder to ${BUCKET}${TARGET_VERSION}"
    aws s3 cp "${SYNC_SOURCE}" "${SYNC_TARGET}" --recursive --profile multitenant &&
    echo "🌍 URL: https://${BUCKET}${TARGET_VERSION}/index.html"

    # special cache control for index.html and version.json
    aws s3 cp "${SYNC_SOURCE}/index.html" "${SYNC_TARGET}" --cache-control "max-age=0,no-cache,no-store,must-revalidate" --endpoint-url https://s3-accelerate.amazonaws.com &&
    aws s3 cp "${SYNC_SOURCE}/version.json" "${SYNC_TARGET}" --cache-control "max-age=0,no-cache,no-store,must-revalidate" --endpoint-url https://s3-accelerate.amazonaws.com
else
    progress "Skip s3 sync..."
fi



# . "${CURRENT_DIR}/upload_devdocs_ui.sh"
