#!/bin/bash
set -euo pipefail

REMOTE_NAME="tradingview-charting"
REMOTE_URL="git@github.com:tradingview/charting_library.git"
PREFIX="web/public/charting_library"
BRANCH="master"

# Detect the default branch if master doesn't exist
echo "Adding remote '$REMOTE_NAME'..."
if git remote get-url "$REMOTE_NAME" &>/dev/null; then
  echo "Remote '$REMOTE_NAME' already exists, skipping."
else
  git remote add "$REMOTE_NAME" "$REMOTE_URL"
fi

echo "Fetching from $REMOTE_URL (this may take a moment)..."
git fetch "$REMOTE_NAME" "$BRANCH"

if [ -d "$PREFIX" ]; then
  echo "'$PREFIX' already exists — pulling latest changes..."
  git subtree pull \
    --prefix="$PREFIX" \
    "$REMOTE_NAME" "$BRANCH" \
    --squash \
    -m "chore: update charting_library from tradingview upstream"
else
  echo "Adding '$PREFIX' for the first time..."
  git subtree add \
    --prefix="$PREFIX" \
    "$REMOTE_NAME/$BRANCH":charting_library \
    --squash \
    -m "chore: add charting_library from tradingview/charting_library"
fi

echo "Done. Files are at: $PREFIX"
