#!/bin/bash

# ============ Init variables ============

# Базовый путь для сохранения бекапов.
BASE_BACKUP_DIR='/root/backups'

# Токен Yandex.Disk.
YD_TOKEN='AQAAAAAB....'

# Пароль от пользователя root СУБД MySQL. Если она не используется, оставьте пустым.
MYSQL_ROOT_PASSWORD='password'

# Делать дампы СУБД PostgreSQL?
# Пустая строка - нет
# "1" - да
USE_POSTGRESQL=''

# Список директорий, которые необходимо бекапить.
# В данном примере будет забекаплена директория /etc как архив etc.tar.gz и
# все поддиректории /var/www с соответствующими именами.
declare -a DIRS_FOR_BACKUP=('/etc' '/home/user/www/*');

# Размеры чанков (т.к. максимальный размер файлов ограничен, то необходимо
# разрезать архив на несколько частей. Чанк - и есть эта часть).
SPLIT_BY='200MiB'

# ==================================================
# ============ DO NOT CHANGE CODE BELOW ============
# ==================================================

# ============ Init internal variables ============

TIMESTAMP=$(date +"%F")
BACKUP_DIR="$BASE_BACKUP_DIR/$TIMESTAMP"

# ============ Start ============

if [ -z "${YD_TOKEN}" ]; then
    echo "Set YD_TOKEN variable!"
    return 0
fi

function string_replace {
    echo "${1//\*/$2}"
}

function upload()
{
	
    LOCAL_FILE_PATH=$1
    REMOTE_DIRECTORY=$(echo $2 | sed 's/\//%2F/g')
    REMOTE_DIRECTORY2=$(echo $2 | sed 's/\//\n/g')
    REMOTE_FILE_NAME=$3
	# recursive dir create
    CURR_REMOTE_PATH=""
    for word in $REMOTE_DIRECTORY2; do
        CURR_REMOTE_PATH="$CURR_REMOTE_PATH%2F$word"
        curl -X PUT -s -H "Authorization: OAuth $YD_TOKEN" "https://cloud-api.yandex.net/v1/disk/resources/?path=app:$CURR_REMOTE_PATH"
    done
    # upload url
    UPLOAD_URL=`curl -s -H "Authorization: OAuth $YD_TOKEN" "https://cloud-api.yandex.net:443/v1/disk/resources/upload/?path=app:%2F$REMOTE_DIRECTORY%2F$REMOTE_FILE_NAME&overwrite=true" | grep -E -o '"href":"([^"]+)"' | cut -f 4 -d '"' `
    # upload file
    curl -s -T $LOCAL_FILE_PATH -H "Authorization: OAuth $YD_TOKEN" $UPLOAD_URL
}

# ============ Backup files ============

mkdir -p "$BACKUP_DIR/files"

for d in ${DIRS_FOR_BACKUP[@]}; do
    for f in "$d"; do
        fshort=$( basename $f )
        echo "Backuping '$f'..."
        tar cz -C $f . | split -b $SPLIT_BY - $BACKUP_DIR/files/$fshort.tgz_
        for x in $( ls $BACKUP_DIR/files ); do
            echo "Uploading '$fshort'..."
            upload "$BACKUP_DIR/files/$x" "$TIMESTAMP/files" "$x"
            rm $BACKUP_DIR/files/$x
        done
    done
done

# ============ Dump all MySQL ============

if [[ ! -z "${MYSQL_ROOT_PASSWORD}" ]]; then
    mkdir -p "$BACKUP_DIR/mysql"
    dblist=`mysql -u root -p$MYSQL_ROOT_PASSWORD -e "show databases" | sed -n '2,$ p'`
    for db in $dblist; do
        mysqldump -u root -p$MYSQL_ROOT_PASSWORD $db | gzip --best > $BACKUP_DIR/mysql/$db.sql.gz
        split -b $SPLIT_BY $BACKUP_DIR/mysql/$db.sql.gz $BACKUP_DIR/mysql/$db.sql.gz_
        rm $BACKUP_DIR/mysql/$db.sql.gz
        for x in $( ls $BACKUP_DIR/mysql ); do
            upload "$BACKUP_DIR/mysql/$x" "$TIMESTAMP/mysql" "$x"
            rm $BACKUP_DIR/mysql/$x
        done
    done
fi

# ============ Dump all PostgreSQL ============

if [[ ! -z "${USE_POSTGRESQL}" ]]; then
    mkdir -p "$BACKUP_DIR/postgresql"
    dblist=$( sudo -u postgres -H -- psql -lt |awk '{ print $1}' |grep -vE '^\||^-|^List|^Name|template[0|1]' )
    for db in $dblist
    do
        echo "Backuping postgresql database: $db"
        sudo -u postgres -H -- pg_dump $db | gzip -c > $BACKUP_DIR/postgresql/$db.sql.gz
        split -b $SPLIT_BY $BACKUP_DIR/postgresql/$db.sql.gz $BACKUP_DIR/postgresql/$db.sql.gz_
        rm $BACKUP_DIR/postgresql/$db.sql.gz
        for x in $( ls $BACKUP_DIR/postgresql ); do
            upload "$BACKUP_DIR/postgresql/$x" "$TIMESTAMP/postgresql" "$x"
            rm $BACKUP_DIR/postgresql/$x
        done
    done
fi

# ============ remove all ============

rm -rf $BACKUP_DIR
