#!/bin/bash

function print_help_and_exit
{
cat >&2 << 'EOF'

'voronota-js-pdb-utensil-rename-chains' script reads structure, renames chains by, outputs structure.

Options:
    --rule                    string  *  chain renaming rule
    --help | -h                          flag to display help message and exit

Standard input:
    structure in PDB format
    
Standard output:
    structure in PDB format
    
Examples:
    
    cat "./model.pdb" | voronota-js-pdb-utensil-rename-chains --rule 'A=B,B=A' > "./result.pdb"
    
    cat "./model.pdb" | voronota-js-pdb-utensil-rename-chains 'A=B,B=A' > "./result.pdb"
    
    cat "./model.pdb" | voronota-js-pdb-utensil-rename-chains 'C' > "./result_with_all_chains_named_C.pdb"
    
    cat "./model.pdb" | voronota-js-pdb-utensil-rename-chains '_invert_case' > "./result.pdb"
    
    cat "./model.pdb" | voronota-js-pdb-utensil-rename-chains 'A2=B' > "./result.pdb"
    
EOF
exit 1
}

readonly ZEROARG=$0
ALLARGS=("$@")

if [ -z "$1" ]
then
	print_help_and_exit
fi

if [[ $ZEROARG == *"/"* ]]
then
	cd "$(dirname ${ZEROARG})"
	export PATH="$(pwd):${PATH}"
	cd - &> /dev/null
fi

export LC_ALL=C

command -v voronota-js &> /dev/null || { echo >&2 "Error: 'voronota-js' executable not in binaries path"; exit 1; }

RULE=""
RULE_READ="false"
AS_ASSEMBLY="true"
HELP_MODE="false"

while [[ $# > 0 ]]
do
	OPTION="$1"
	OPTARG="$2"
	shift
	case $OPTION in
	--rule)
		RULE="$OPTARG"
		RULE_READ="true"
		shift
		;;
	--not-as-assembly)
		AS_ASSEMBLY="false"
		;;
	-h|--help)
		HELP_MODE="true"
		;;
	*)
		if [ "$RULE_READ" == "false" ]
		then
			RULE="$OPTION"
			RULE_READ="true";
		else
			echo >&2 "Error: invalid command line option '$OPTION'"
			exit 1
		fi
		;;
	esac
done

if [ "$HELP_MODE" == "true" ]
then
	print_help_and_exit
fi

if [ -z "$RULE" ]
then
	echo >&2 "Error: no rule provided"
	exit 1
fi

readonly TMPLDIR=$(mktemp -d)
trap "rm -r $TMPLDIR" EXIT

cat > "$TMPLDIR/input.pdb"

if [ ! -s "$TMPLDIR/input.pdb" ]
then
	echo >&2 "Error: no stdin data"
	exit 1
fi

{
cat << EOF
var params={}
params.input_file='$TMPLDIR/input.pdb';
params.output_file='$TMPLDIR/output.pdb';
params.rule='$RULE';
params.as_assembly='$AS_ASSEMBLY';
EOF

cat << 'EOF'
voronota_setup_defaults("-no-load-voromqa-potentials", "-no-load-more-atom-types", "-no-load-mock-voromqa-potential -include-heteroatoms");
voronota_assert_full_success("Failed to setup defaults");

voronota_import("-file", params.input_file, "-as-assembly", params.as_assembly);
voronota_assert_full_success("Failed to input structure");

voronota_set_chain_name("-use", "[]", "-chain-name", params.rule);
voronota_assert_full_success("Failed to change chain names");

voronota_export_atoms("-as-pdb", "-file", params.output_file);
voronota_assert_full_success("Failed to output structure");
EOF

} \
| voronota-js --no-setup-defaults

if [ ! -s "$TMPLDIR/output.pdb" ]
then
	echo >&2 "Error: no output produced for rule '$RULE'"
	exit 1
fi

cat "$TMPLDIR/output.pdb"

