#!/bin/bash
# Issue #51425
BACKUPDIR=/var/backup
MYSQLRAWDIR=/var/lib/mysql/
PDIR=/etc/sysconfig/ng-backup

while [[ "$1" =~ ^-- ]]; do
        case "$1" in
                --age)
                        AGE=1
                        ;;

                --backup-size)
                        BACKUPSIZE=1
                        ;;
                --raw-size)
                        RAWSIZE=1
                        ;;
                *)
                        "Unknown option '$1'"
                        ;;
        esac
        shift
done


# Case to fail without any arguments??
#if [[ -z $AGE ]] || [[ -z $SIZE ]]; then
#       printf "\e[31mERR:\e[0m Missing options\n" >&2
#       exit 1
#fi

# Source the mysql backup path from ng-backup (if available)
if [[ -f $PDIR ]]; then
        source $PDIR
fi

# This script will fail if there's no argument (database name)
if [[ -z "$1" ]]; then
        printf "\e[31mERR:\e[0m $0 requires a database name\n" >&2
        exit 2
fi

# Security~
# This script should fail if the argument contains metacharacters
if [[ ! "$1" =~ ^[a-zA-Z][-a-zA-Z0-9_]{0,61}[a-zA-Z0-9]$ ]]; then
        printf "\e[31mERR:\e[0m Argument contains metacharacters\n" >&2
        printf "ZBX_UNSUPPORTED\n"
        exit 3
fi

# Follow symlinks and find the date of files in the directory that contain the given file name ending in .sql.bz2 and are larger than 550bytes (i.e. the minimum size non-skeleton database)
# Print only the newest file and print 0 if there are no files matching these arguments
if [[ $AGE -eq 1 ]]; then
        find -H $BACKUPDIR/mysql/sql -type f -name "$1-*.sql.*" -size +550c -printf '%Ts\n' | sort -nr | awk -vMAT=0 'NR==1{MAT=$0; end;}; END{print MAT}'
fi

# Do the same as the previous command, but this time print the file size in bytes
# NOTE!!!: find will print the filename (includes date)... We can then reverse sort the values (first column) - meaning the first line will always be the newest backup
if [[ $BACKUPSIZE -eq 1 ]]; then
        find -H $BACKUPDIR/mysql/sql -type f -name "$1-*.sql.*" -size +550c -printf '%f\t%s\n' | sort --reverse --stable --key 1,1 | awk -vMAT=0 'NR==1{MAT=$2; end;}; END{print MAT}'
fi

# Find the RAW database size
# Only sizes over 80bytes and matching the name given
if [[ $RAWSIZE -eq 1 ]]; then
	# READ: https://dev.mysql.com/doc/refman/5.6/en/identifier-mapping.html
	# For the raw database directory, mysql rewrites meta characters in way which is complex to calculate
	# Here's an attempt to deal with this (based on ascii - which is NOT what mysql ACTUALLY uses... OH GOD WHY WOULD THEY DO THIS???)
	ENCNAME=$(echo "$1" | perl -pe 's/([^_0-9A-Za-z])/sprintf("@%04x", ord($1))/ge;')
        find -L $MYSQLRAWDIR -maxdepth 1 -type d -name "$1" -size +80c -exec du -b '{}' \; | awk -vMAT=0 'NR==1{MAT=$1; end;}; END{print MAT}'
fi
