#!/bin/bash 
#===============================================================================
#
#          FILE:  ansible_template.sh
# 
#         USAGE:  ./ansible_template.sh 
# 
#   DESCRIPTION:  generates ansible vars and jinja2 template from a config file
# 
#       OPTIONS:  <ansible variable prefix> <config filename> [option separator]
#        AUTHOR:  Ryan Schulze (rs), ryan@dopefish.de
#       CREATED:  03/03/2015 09:56:04 PM CST
#      REVISION:  1.2
#===============================================================================

#===============================================================================
# Main
#===============================================================================

Prefix="${1:-}"
ConfigOriginal="${2}"
Separator="${3:- :=}"

usage() {
	echo "Usage: $(basename "${0}") <variable name prefix> <config file> [ <config separator> ]"
	echo
	echo "This small script takes a config file and splits it into a jinja2 template and a yaml file for usage with ansible"
	echo
	echo "Example: $(basename "${0}") greylist mail.foo.bar:/etc/greylistd/config"
	echo
	exit 0
}
if [[ $# -lt 2 ]]; then
	usage
fi

cleanup() {
	rm "${tmpfile}"
	exit 0
}

Template="${ConfigOriginal##*/}.j2"
scp='scp -o connecttimeout=10 -o stricthostkeychecking=no'
ssh='ssh -o connecttimeout=10 -o stricthostkeychecking=no'
tmpfile=$(mktemp)
trap cleanup TERM EXIT

if [[ -f "${ConfigOriginal}" ]] ; then
	cp "${ConfigOriginal}" "./${Template}"	
	cp "${Template}" "${tmpfile}"
elif [[ ${ConfigOriginal} =~ ^.+:.+$ ]] ; then
	$scp -q "${ConfigOriginal}" "${Template}"
	if [[ $? -gt 0 ]] ; then
		echo "Error: '${ConfigOriginal}' could not be accessed ..."
		exit 1
	fi
	cp "${Template}" "${tmpfile}"
	echo "- name: ${Prefix^} template"
  	echo "  template: src={{ item.local }} dest={{ item.remote }} owner={{ item.owner }} group={{ item.group }} mode={{ item.mode }}"
  	echo "  with_items:"
  	$ssh "${ConfigOriginal%%:*}" "stat --format \"    - { local: '${Template}', remote: '${ConfigOriginal#*:}', owner: '%U', group: '%G', mode: '%.4a' }\" \"${ConfigOriginal#*:}\""
	echo
else
	echo "Error: '${ConfigOriginal}' needs to be either an existing local or remote file ..."
	exit 1
fi

while read line
do
	# variable in " " or ' ' (foo = "1")
	if [[ ${line} =~ ^([^#][^\ ]+)[\ ]*[${Separator}][\ ]*[\"\'](.+)[\'\"]$ ]]; then
		VariableName="${Prefix}_${BASH_REMATCH[1]//-/_}"
		VariableName="${VariableName,,}"
		sed -ri "s/^(${BASH_REMATCH[1]}[\ ]*[${Separator}][\ ]*[\"\']).+([\"\'])$/\1{{ ${VariableName} }}\2/" "${Template}"
		printf "%-40s %s\n" "${VariableName}:" "'${BASH_REMATCH[2]}'"
	# 'naked' variable (foo = 1)
	elif [[ ${line} =~ ^([^#][^\ ]+)[\ ]*[${Separator}][\ ]*([^\ ]+)$ ]] ; then
		VariableName="${Prefix}_${BASH_REMATCH[1]//-/_}"
		VariableName="${VariableName,,}"
		sed -ri "s/^(${BASH_REMATCH[1]}[\ ]*[${Separator}][\ ]*).+$/\1{{ ${VariableName} }}/" "${Template}"
		printf "%-40s %s\n" "${VariableName}:" "'${BASH_REMATCH[2]}'"
	fi
done < "${tmpfile}"
echo
