<%- if @kernel == 'Linux' -%>
#!/bin/bash
<%- else -%>
#!/bin/sh
<%- end -%>
#
# A wrapper for Xtrabackup

ROTATE=<%= [ Integer(@backuprotate) - 1, 0 ].max %>
DIR=<%= @backupdir %>

# Ensure backup directory exist.
mkdir -p $DIR

<%- if @kernel == 'Linux' -%>
set -o pipefail
<%- end -%>

<% if @prescript -%>
  <%- [@prescript].flatten.compact.each do |script| %>
<%= script %>
  <%- end -%>
<% end -%>


cleanup()
{
    find "${DIR}/" -mindepth 1 -maxdepth 1 -mtime +${ROTATE} -print0 | xargs -0 -r rm -rf
}

<% if @delete_before_dump -%>
cleanup
<% end -%>


<%- _innobackupex_args = '' -%>

<%- if @backupuser and @backuppassword_unsensitive -%>
  <%- _innobackupex_args = '--user="' + @backupuser + '" --password="' + @backuppassword_unsensitive + '"' -%>
<%- end -%>

<%- if @backupcompress -%>
  <%- _innobackupex_args = _innobackupex_args + ' --compress' -%>
<%- end -%>

<%- if @backupdatabases and @backupdatabases.is_a?(Array) and !@backupdatabases.empty? -%>
  <%- _innobackupex_args = _innobackupex_args + ' --databases="' + @backupdatabases.join(' ') + '"' -%>
<%- end -%>

<%- if @optional_args and @optional_args.is_a?(Array) -%>
  <%- @optional_args.each do |arg| -%>
    <%- _innobackupex_args = _innobackupex_args + ' ' + arg -%>
  <%- end -%>
<%- end -%>

<%= @backupmethod -%> <%= _innobackupex_args %> $@


<% unless @delete_before_dump -%>
if [ $? -eq 0 ] ; then
    cleanup
    <% if @backup_success_file_path -%>
    touch <%= @backup_success_file_path %>
    <% end -%>
fi
<% end -%>


<% if @postscript -%>
  <%- [@postscript].flatten.compact.each do |script| %>
<%= script %>
  <%- end -%>
<% end -%>
