#!/bin/bash

set -e

# ---- Setting variables ----
source_tt2=$1
local_path=$(pwd)
file_exist=0

# ---- functions definition ----
usage() {
  echo "Usage: $0 /PATH/file.tt2

Creates the .customtt.tt2 file out from the passed '/PATH/file.tt2'.

  /PATH/file.tt2        Can be a tt2 fullpath or local tt2 file. In that case customtt is
                        created in the current path.

Example: $0 /etc/ngcp-config/templates/etc/kamailio/proxy/kamailio.cfg.tt2"

}

check_source_file()
{
  if [[ -f "${source_tt2}" && "${source_tt2: -4}" == ".tt2" ]]; then
    file_exist=1
  else
    file_exist=0
  fi
}

create_customtt()
{
  if [ ${file_exist} == 1 ]; then
    cp "${source_tt2}" "${source_tt2::-4}.customtt.tt2"
    echo "Customtt created: '${source_tt2::-4}.customtt.tt2'"
  else
    cp "${local_path}/${source_tt2}" "${local_path}/${source_tt2::-4}.customtt.tt2"
    echo "Customtt created: '${local_path}/${source_tt2::-4}.customtt.tt2'"
  fi
}

# ---- main ----
if [[ -n "${source_tt2}" ]]; then
  check_source_file
  if [ "${file_exist}" == 1 ]; then
    create_customtt
  else
    echo "ERR: Cannot locate file '${source_tt2}' or file is not a '.tt2'"
  fi
else
  usage
fi

exit 0
