#!/bin/zsh

# Creates a SQL file for database schema updates and adds it the changelog file.

local ticket_num=$1
local task_name=$2
local dev_username=$3
local changelog='./royalty_accounting/build/db.changelog-master.xml'

# leave args blank and get prompted for them
if [[ -z "$ticket_num" || -z "$task_name" ||  -z "$dev_username" ]]; then
  [[ -z "$task_name" ]] && read "?Enter task_name: " task_name
  [[ -z "$ticket_num" ]] && read "?Enter ticket_num: " ticket_num
  [[ -z "$dev_username" ]] && read "?Enter dev_username: " dev_username
fi

local template="./scripts/templates/liquibase.sql.template"
local filename="./royalty_accounting/build/changelog/ddl/${ticket_num}_${task_name}.sql"

# Create the ddl file from template
sed \
  -e "s/%dev_username/$dev_username/g" \
  -e "s/%ticket_num/$ticket_num/g" \
  -e "s/%task_name/$task_name/g" \
  "$template" > "$filename"

echo -e "\nSQL file created: $filename\n"

# Add the new SQL file to the changelog
sed -i '' "$ s|</databaseChangeLog>|  <include file=\"changelog/ddl/${filename##*/}\"/>\n</databaseChangeLog>|" $changelog

echo "Updated changelog: $changelog"
