#!/usr/bin/env bash

__rvm_record_install()
{

  local recorded_ruby_name rvm_install_record_file rvm_install_command

  [[ -z "$1" ]] && return

  recorded_ruby_name="$("$rvm_scripts_path/tools" strings "$1")"

  rvm_install_record_file="$rvm_path/config/installs"

  rvm_install_command=$(printf "$recorded_ruby_name $rvm_install_args\n")

  [[ ! -f "$rvm_install_record_file" ]] && \touch "$rvm_install_record_file"

  \rm -f "$rvm_install_record_file.tmp"

  \grep -v "^$recorded_ruby_name " < "$rvm_install_record_file" \
    > "$rvm_install_record_file.tmp"

  echo "$rvm_install_command" >> "$rvm_install_record_file.tmp"

  \rm -f "$rvm_install_record_file"

  \mv "$rvm_install_record_file.tmp" "$rvm_install_record_file"

  return 0
}

__rvm_remove_install_record()
{
  local recorded_ruby_name rvm_install_record_file

  recorded_ruby_name="$("$rvm_scripts_path/tools" strings "$1")"

  rvm_install_record_file="$rvm_path/config/installs"

  if [[ -s "$rvm_install_record_file" ]]; then

    \mv "$rvm_install_record_file" "$rvm_install_record_file.tmp"

    \grep -v "^$recorded_ruby_name " < "$rvm_install_record_file.tmp" \
      > "$rvm_install_record_file"

    \rm -f "$rvm_install_record_file.tmp"
  fi

  return 0
}

__rvm_recorded_install_command()
{
  local recorded_ruby_name recorded_ruby_match

  recorded_ruby_name="$("$rvm_scripts_path/tools" strings "$1" \
    | awk -F"${rvm_gemset_separator:-"@"}" '{print $1}')"

  [[ -z "$recorded_ruby_name" ]] && return 1

  recorded_ruby_match="^$recorded_ruby_name "

  if [[ -s "$rvm_path/config/installs" ]] \
    && \grep "$recorded_ruby_match" "$rvm_path/config/installs" >/dev/null 2>&1 ; then

    \grep "$recorded_ruby_match" < "$rvm_path/config/installs" | head -n1

  else
    return 1
  fi
  return $?
}

