#!/bin/bash

# Required to be executed from SKD root path
KERNELS_PATH="$(pwd)/kernels"
MKS_PATH="${KERNELS_PATH}/mk"

# The function to create local MKs
create_local_mk()
{
  SEARCH_STR="     PATH_VALUES       = ( '..' )"
  REPLACE_STR="     PATH_VALUES       = ( '$KERNELS_PATH' )"

  # Extract the filename and extension from the file path
  filename=$(basename "$1")

  # Extract the extension from file path
  extension="${filename##*.}"

  # Extract the filename without the extension
  filename="${filename%.*}"

  local_suffix="local"
  if [ "$extension" = "TM" ]; then
      local_suffix="LOCAL"
  fi

  local_mk="${filename}_${local_suffix}.${extension}"

  echo "Creating $local_mk"
  if [ -f "$local_mk" ]; then
    rm "$local_mk"
  fi

  while IFS= read -r line;do
    if [[ "$line" = $SEARCH_STR* ]];
    then
      echo "$REPLACE_STR" >> "$local_mk"
    else
      echo "$line" >> "$local_mk"
    fi
  done < "$1"
}

# Check OS Platform and do specific platform steps
case "$OSTYPE" in
  solaris*) echo "Platform: SOLARIS Not supported" 
			exit 1 ;;
			
  darwin*)  echo "Platform: OSX" ;; 
  
  linux*)   echo "Platform: LINUX" ;;
  
  bsd*)     echo "Platform: BSD Not supported" 
			exit 1 ;;
			
  msys*)    echo "Platform: WINDOWS"
			curr_path=$(pwd -W)
			KERNELS_PATH="${curr_path}/kernels" 
			echo "KERNELS_PATH: $KERNELS_PATH" ;;
			
  *)        echo "Platform: unknown: $OSTYPE Not supported" 
			exit 1 ;;
esac

# Check that KERNELS_PATH doesn't have spaces:
case "$KERNELS_PATH" in 
    *[[:space:]]*) 
        echo "In order to update the local Meta-Kernels, the SKD path: $KERNELS_PATH should not have white spaces. Try moving the SKD to another location." >&2
        exit 1
        ;; 
esac

# Go to MK folder
if [ -d "$MKS_PATH" ]
then
  cd "$MKS_PATH" || exit 1

  echo "Removing old local Meta-Kernels..."
  find . -iname '*_local.tm' | while read mk_file;  # For each _local.tm with case insensitive
  do
    rm "$mk_file"
    echo "Removed $mk_file"
  done

  echo "Creating updated local Meta-Kernels..."
  find . -iname '*.tm' | while read mk_file;  # For each .tm with case insensitive
  do
    mk_filename=$(basename "$mk_file")

    extension="${mk_filename##*.}"
    local_suffix="local"
    if [ "$extension" = "TM" ]; then
        local_suffix="LOCAL"
    fi

    if [[ $mk_filename != *"_${local_suffix}."*  ]];
    then
      create_local_mk "$mk_file"
    fi
  done

  echo "Local Meta-Kernels updated successfully..."
  exit 0

else
  echo "Invalid path: $MKS_PATH , aborted."
  exit 1
fi

