#!/bin/zsh

# Given internal user ids, make their Abacus profiles read only.

local user_ids=$1
local ticket_num=$2
local dev_username=$3
local dev_id=$4

# Leave args blank to get prompted for them
if [[ -z "$user_ids" || -z "$ticket_num" || -z "$dev_username" || -z "$dev_id" ]]; then
  [[ -z "$user_ids" ]] && read "?Enter user_ids (comma separated): "
  [[ -z "$ticket_num" ]] && read "?Enter ticket_num: "
  [[ -z "$dev_username" ]] && read "?Enter dev_username: "
  [[ -z "$dev_id" ]] && read "?Enter dev_id: "
fi

ids_to_cypher_objects() {
  local ids=(${(s:,:)1})
  local offset=0

  for id in "${ids[@]}"; do
    echo "    {uuid: '$id', offset: $offset},"
    ((offset++))
  done | sed '$ s/,$//'  # Remove trailing comma from last line
}

local template="./scripts/templates/make-abacus-profiles-readonly.template"
local filename="./neo4j/neo4j-orchard/build/changelog/dml/$ticket_num-make-abacus-profiles-readonly.cypher"

# Prepare replacement values
local quoted_ids=${"$(printf "'%s', " ${(s:,:)user_ids})"%, }
local user_id_objects=$(ids_to_cypher_objects "$user_ids")

# Create a temporary file for the first pass
local temp_file="${filename}.tmp"

# Pass 1: Use sed for simple string replacements
# Using ~ as delimiter to avoid conflicts with slashes in paths/ids
sed \
  -e "s~%dev_username~$dev_username~g" \
  -e "s~%dev_id~$dev_id~g" \
  -e "s~%ticket_num~$ticket_num~g" \
  -e "s~%user_ids~$quoted_ids~g" \
  "$template" > "$temp_file"

# Pass 2: Use shell loop for the multiline object replacement
while IFS= read -r line || [[ -n "$line" ]]; do
  if [[ "$line" == *"%user_id_cypher_objects"* ]]; then
    echo "$user_id_objects"
  else
    print -r -- "$line"
  fi
done < "$temp_file" > "$filename"

# Cleanup
rm "$temp_file"

echo "\nCypher file created: $filename\n"
