#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

SCRIPT_PATH=$(cd "$(dirname "$0")" && pwd)
VERSIONED_DOCS="$SCRIPT_PATH/versioned_docs"
VERSIONED_SIDEBARS="$SCRIPT_PATH/versioned_sidebars"

mkdir -p "$VERSIONED_DOCS"
mkdir -p "$VERSIONED_SIDEBARS"

# Configure the remote repository URL and temporary directory
REPO_URL="https://github.com/apache/fluss.git"
TEMP_DIR=$(mktemp -d)

# Check if the temporary directory was successfully created
if [ ! -d "$TEMP_DIR" ]; then
  echo "Failed to create temporary directory"
  exit 1
fi

echo "Cloning remote repository to temporary directory: $TEMP_DIR"
git clone "$REPO_URL" "$TEMP_DIR"

# Enter the temporary directory
cd "$TEMP_DIR" || { echo "Failed to enter temporary directory"; exit 1; }


# Match branches in the format "release-x.y"
regex='release-[0-9]+\.[0-9]+$'                          # Regular expression to match release-x.y
branches=$(git branch -a | grep -E "$regex"| sort -r)    # Filter branches that match the criteria

# Exit the script if no matching branches are found
if [ -z "$branches" ]; then
  echo "No branches matching 'release-x.y' format found"
  exit 0
fi

echo "Matched branches:"
echo "$branches"

##################################################################################################
# Generate versions.json file
##################################################################################################

# Initialize JSON array
versions_json="["

# Iterate over each matched branch
for branch in $branches; do
  # Extract the version number part (remove the "release-" prefix)
  version=$(echo "$branch" | sed 's|remotes/origin/release-||')

  # Add to the JSON array
  versions_json+="\"$version\", "
done

# Remove the last comma and space, and close the JSON array
versions_json="${versions_json%, }]"
echo "Generated the versions JSON: $versions_json"

# Output to versions.json file
echo "$versions_json" > "$SCRIPT_PATH/versions.json"
echo "Operation completed! Versions information has been saved to $SCRIPT_PATH/versions.json file."

##################################################################################################
# Generate versioned sidebars JSON file
##################################################################################################

sidebar_json='{
 "docsSidebar": [
   {
     "type": "autogenerated",
     "dirName": "."
   }
 ]
}'

# handle OS-specific cp command
if [ "$(uname)" == "Darwin" ]; then
  CP_CMD="cp -R website/docs/ "
else
  CP_CMD="cp -r website/docs/* "
fi

# Iterate over each matched branch
for branch in $branches; do
  # Remove the remote branch prefix "remotes/origin/"
  clean_branch_name=$(echo "$branch" | sed 's|remotes/origin/||')
  version=$(echo "$branch" | sed 's|remotes/origin/release-||')

  echo "Processing branch: $clean_branch_name"

  # 检出分支
  git checkout "$clean_branch_name" || { echo "Failed to checkout branch: $clean_branch_name"; continue; }

  version_sidebar_file="$VERSIONED_SIDEBARS/version-$version-sidebars.json"
  echo "$sidebar_json" > "$version_sidebar_file" || { echo "Failed to generate sidebar file for version '$version'"; continue; }
  echo "Generated sidebar file for version '$version': $version_sidebar_file"

  # Check if the website/docs directory exists
  if [ -d "website/docs" ]; then
    # Create the target subdirectory (named after the branch)
    version_dir="$VERSIONED_DOCS/version-$version"
    mkdir -p "$version_dir"

    # Copy the website/docs directory to the target directory
    $CP_CMD "$version_dir/" || { echo "Failed to copy for branch: $clean_branch_name"; continue; }
    echo "Copied documentation for branch '$clean_branch_name' to '$version_dir'"
  else
    echo "The website/docs directory does not exist in branch '$clean_branch_name', skipping..."
  fi
done

# Clean up the temporary directory
echo "Cleaning up temporary directory: $TEMP_DIR"

rm -rf "$TEMP_DIR"

echo "Build versioned docs completed!"