#!/bin/bash
#
# Copyright (c) 2020 Bubble, Inc.  All rights reserved. For personal (non-commercial) use, see license: https://getbubblenow.com/bubble-license/
#
#
# Request a URL via the reverse proxy
#
# Usage:  proxy url outfile
#
# Environment variables
#
#   BUBBLE_API     : which API to use. Default is local (http://127.0.0.1:PORT, where PORT is found in .bubble.env)
#   BUBBLE_USER    : account to use. Default is root
#   BUBBLE_PASS    : password for account. Default is root
#   BUBBLE_SCRIPTS : location of run.sh script. Default is to assume it is in the same directory containing this script
#
SCRIPT="${0}"
SCRIPT_DIR=$(cd $(dirname ${SCRIPT}) && pwd)
. ${SCRIPT_DIR}/bubble_common

URL="${1:?no URL provided}"
OUTFILE="${2:?no outfile provided}"
RAW=${3:-true}

if [[ "${URL}" =~ http:// ]] ; then
  URL="http/$(echo -n ${URL} | cut -d/ -f3-)"
elif [[ "${URL}" =~ https:// ]] ; then
  URL="https/$(echo -n ${URL} | cut -d/ -f3-)"
else
  URL="http/$(echo -n ${URL} | cut -d/ -f3-)"
fi

PROXY_SCRIPT="${SCRIPT_DIR}/../scripts/proxy.json"
if [[ ! -f "${PROXY_SCRIPT}" ]] ; then
  die "proxy API script not found: ${PROXY_SCRIPT}"
fi

echo '{"URL": "'"${URL}"'", "OUTFILE": "'"${OUTFILE}"'", "RAW": "'"${RAW}"'"}' \
    | ${SCRIPT_DIR}/bscript ${PROXY_SCRIPT} --vars -
