namespace :db do

desc "Backup Magento 2 database"
task :backup do
    # Backup the database with a timestamp
    on roles :all do
        # Check if the backup directory exists and if not create it
        if test("[ ! -d #{fetch(:backupdir)} ]")
            execute :mkdir, "-p", fetch(:backupdir)
        end

        invoke 'db:mag_db_backup'
        invoke 'db:wp_db_backup'
    end
end

desc "Backup Magento database"
task :mag_db_backup do
    on roles :all do
        info "Backing up Magento database."
        execute :n98magerun, 'db:dump', "--root-dir='#{fetch(:mage_root)}'",
                                        '--compression="gzip"',
                                        '--strip="@log @sessions"',
                                        '--force', "#{fetch(:backupdir)}/#{fetch(:date_path)}_m2.sql.gz"
    end
end

desc "Backup WordPress database"
task :wp_db_backup do
    # Backup the database with a timestamp
    on roles :all do
        if (fetch(:wp_backup).to_s == "true")
            info "Backing up WordPress database."
            execute :n98magerun, 'db:dump', "--root-dir='#{fetch(:mage_root)}'",
                                        '--compression="gzip"',
                                        '--connection="wordpress"',
                                        '--force', "#{fetch(:backupdir)}/#{fetch(:date_path)}_wp.sql.gz"
        else
            info "WordPress backup set to false"
        end
    end
end

desc "Clean up old backups"
task :cleanup do
    on roles :all do
        backups = capture(:ls, "-x", "#{fetch(:backupdir)}").split
        valid, invalid = backups.partition { |e| /^\d{14}/ =~ e }

        info "Found #{valid.count} valid backups."

        if (valid.count >= fetch(:keep_backups).to_i)
            info "Keeping #{fetch(:keep_backups)} of #{valid.count} backups."
            files = (valid - valid.last(fetch(:keep_backups).to_i)).map do |backup|
                "#{fetch(:backupdir)}" + "/" + (backup).to_s
            end

            if files.any?
                files.each_slice(100) do |files_batch|
                    execute :rm, "-f", *files_batch
                end
            end
        end
    end
end

end