set -eux  ## important for unbound variable ?

## Require these to be set
# MYSQL_ROOT_PASSWORD=
# MYSQL_CONTAINER=

[ "${MYSQL_ROOT_PASSWORD}" ] || {
    echo "Error: you must set \$MYSQL_ROOT_PASSWORD prior to running this script." >&2
    exit 1
}

[ "${MYSQL_CONTAINER}" ] || {
    echo "Error: you must set \$MYSQL_CONTAINER prior to running this script." >&2
    exit 1
}


##
## Init, to setup passwordless connection to mysql
##

type -p mysql >/dev/null || {
    case $(lsb_release -is) in
        Debian)
            case $(lsb_release -rs) in
                10)
                    apt-get install -y default-mysql-client </dev/null
                    ;;
                *)
                    apt-get install -y mysql-client </dev/null
                    ;;
            esac
            ;;
        Ubuntu)
            apt-get install -y mysql-client </dev/null
            ;;
    esac
}

if ! [ -e "/root/.my.cnf" ]; then
    cat <<EOF > ~/.my.cnf
[client]
password=${MYSQL_ROOT_PASSWORD}
EOF
    chmod 600 ~/.my.cnf
fi

##
## installation of the mysql-backup script
##


apt-get install -y kal-shlib-{core,pretty,common} </dev/null
ln -sf "${PWD}/resources/bin/mysql-backup" /usr/local/sbin/mysql-backup


##
## Connection to cron
##


depends cron
cat <<EOF > /etc/cron.d/mysql-backup
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

0 * * * *   root   /usr/local/sbin/mysql-backup --host \$(docker-ip "$MYSQL_CONTAINER" 2>/dev/null | sed -r 's/ +/ /g' | cut -f 3 -d " ") | logger -t mysql-backup

EOF


##
## Connection with backup
##

if type -p mirror-dir >/dev/null 2>&1; then
    [ -d "/etc/mirror-dir" ] || {
        echo "'mirror-dir' is installed but no '/etc/mirror-dir' was found." >&2
        exit 1
    }
    depends shyaml

    if ! sources=$(shyaml get-values default.sources < /etc/mirror-dir/config.yml); then
        echo "Couldn't query 'default.sources' in '/etc/mirror-dir/config.yml'." >&2
        exit 1
    fi

    if ! echo "$sources" | grep "^/var/backups/mysql$" 2>/dev/null; then
        sed -i '/sources:/a\  - /var/backups/mysql' /etc/mirror-dir/config.yml
        cat <<EOF >> /etc/mirror-dir/config.yml
/var/backups/mysql:
  exclude:
    - "/*.inprogress"
EOF
    fi
else
    echo "warn: 'mirror-dir' not installed, backup won't be sent" >&2
fi