%echo "#!/bin/bash"

set -e
%for %%machine in %%machined.machines
  %set %%nor_machine = %%normalize_family(%%machine)
  %set tls_dir = %%machined['machine_' + %%nor_machine]['tls_dir_' + %%nor_machine]
  %if %%tls_dir
%break
  %end if
%end for
%if %%tls_dir
  %set %%dst_dir = %%machined['machine_' + %%normalize_family(%%rougail_variable)]['config_dir_' +  %%normalize_family(%%rougail_variable)]
  %set %%src_dir = %%tls_dir + "/machines/" + %%rougail_variable
  %if 'certificates' in %%extra_variables and %%rougail_variable in %%extra_variables['certificates']
if [ -d "%%dst_dir" ] && [ -d "%%src_dir" ]; then
    %for %%certificate in %%extra_variables['certificates'][%%rougail_variable]
      %set %%files = [%%certificate.name]
	  %if %%certificate.provider == 'autosigne'
	    %%files.append(%%certificate.authority)
	  %end if
      %if 'private' in %%certificate
        %%files.append(%%certificate.private)
      %end if
      %for %%file in %%files
    src_file="%%{src_dir}%%file"
    dst_file="%%{dst_dir}%%file"
    dst_dir=$(dirname "$dst_file")
    mkdir -p "$dst_dir"
# ne fonctionne pas avec revprox :/
#    a=1
#    while [ ! -f "$src_file" ]; do
#        a=$((a+1));
#        if [ $a = 120 ]; then
#            break
#        fi 
#        sleep 1
#    done
    cp -f "$src_file" "$dst_file"
    chown root: "$dst_file"
    chmod 700 "$dst_file"

      %end for
    %end for
fi
  %end if
%end if
exit 0