#!/bin/bash

# Function to create symbolic links and copy .js files
manage_files() {
  # Define the source (folder a) and destination (folder b)
  folder_a="$1"
  folder_b="$2"

  # Ensure both folders exist
  if [[ ! -d "$folder_a" ]]; then
    echo "Source folder '$folder_a' does not exist!"
    return 1
  fi

  if [[ ! -d "$folder_b" ]]; then
    echo "Destination folder '$folder_b' does not exist!"
    return 1
  fi

  # Get the absolute paths of the source and destination folders
  abs_folder_a=$(realpath "$folder_a")
  abs_folder_b=$(realpath "$folder_b")

  # 1. Create symbolic links for files in folder_a to folder_b with absolute paths
  for file in "$abs_folder_a"/*; do
    # Check if it's a regular file
    if [[ -f "$file" ]]; then
      filename=$(basename "$file")
      destination="$abs_folder_b/$filename"

      # Check if the file already exists in folder_b
      if [[ ! -e "$destination" ]]; then
        # Create a symbolic link in folder_b with absolute paths
        ln -s "$file" "$destination"
        echo "Linked '$file' to '$destination'"
      else
        echo "File '$destination' already exists, skipping..."
      fi
    fi
  done

  # 2. Remove all symbolic links to .js files in folder_b
  find "$abs_folder_b" -type l -name "*.js" -exec rm {} \;
  echo "All symbolic links to .js files have been removed."

  # 3. Copy missing .js files from folder_a to folder_b
  for file in "$abs_folder_a"/*.js; do
    # Ensure it is a regular file
    if [[ -f "$file" ]]; then
      filename=$(basename "$file")
      destination="$abs_folder_b/$filename"

      # Check if the file already exists in folder_b
      if [[ ! -e "$destination" ]]; then
        # Copy the .js file from folder_a to folder_b
        cp "$file" "$destination"
        echo "Copied '$file' to '$destination'"
      else
        echo "File '$destination' already exists, skipping..."
      fi
    fi
  done
}

# Example of calling the function on multiple folder pairs

manage_files "./chess-server-lib/common/models" "./cihsr-server/cihsr/models"
manage_files "./chess-server-lib/common/lib/vmodel" "./cihsr-server/cihsr/lib/vmodel"

rm "./cihsr-server/cihsr/models/labrtfresult.js"
rm "./cihsr-server/cihsr/models/dataimport.js"
rm "./cihsr-server/cihsr/models/birthcertificate.js"
rm "./cihsr-server/cihsr/models/alternatemap.js"
rm "./cihsr-server/cihsr/models/labcollection.js"
rm "./cihsr-server/cihsr/models/purchasereturn.js"
rm "./cihsr-server/cihsr/models/purchasereturnitem.js"
rm "./cihsr-server/cihsr/models/journalgroup.js"
rm "./cihsr-server/cihsr/models/sageopbill.js"
rm "./cihsr-server/cihsr/models/elixirlaborder.js"
rm "./cihsr-server/cihsr/models/pacsorderitem.js"