#!/bin/bash
set -e

TARGET=latest
APPLY_CODE=false
APPLY_GRANTS=false
ENVIRONMENT=testing
CHECK_MIGRATION=false
SQLTYPES=""

function log {
    echo "$(date --iso-8601=ns)	$@"
}

POSITIONAL=()
while [[ $# -gt 0 ]]; do
    key="$1"

    case $key in
        -e|--evironment)
        ENVIRONMENT="$2"
        shift; shift
        ;;
        -t|--target)
        TARGET="$2"
        shift; shift
        ;;
        -c|--code)
        APPLY_CODE=true
        shift
        ;;
        -g|--grants)
        APPLY_GRANTS=true
        shift
        ;;
        -t|--check)
        CHECK_MIGRATION=true
        shift
        ;;
        *)    # unknown option
        POSITIONAL+=("$1") # save it in an array for later
        shift # past argument
        ;;
    esac
done

if [ "$ENVIRONMENT" == "testing" ]; then
    PG_ADMIN_USER=disk_admin
    PG_ADMIN_PASSWORD=$(SUDO_USER=$SSH_USER yav get version sec-01csyf7xdpt7fwesehtm8wzze4 -o $PG_ADMIN_USER)
    PG_COMMON_ADMIN_USER=disk
    PG_COMMON_ADMIN_PASSWORD=$(SUDO_USER=$SSH_USER yav get version sec-01csyf7xdpt7fwesehtm8wzze4 -o $PG_COMMON_ADMIN_USER)
    SHARPEI=mpfs-sharpei.dst.yandex.net
    DBS="diskdb disk_commondb"
    GRANTS="GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA disk TO disk;
        GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA disk TO disk;
        GRANT USAGE ON SCHEMA disk TO disk;
        GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA disk TO disk;
        GRANT USAGE ON SCHEMA code TO disk;
        GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA code TO disk;
        GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA code TO disk;"
elif [ "$ENVIRONMENT" == "stable" ] || [ "$ENVIRONMENT" == "production" ]; then
    PG_ADMIN_USER=disk_mpfs
    PG_ADMIN_PASSWORD=$(SUDO_USER=$SSH_USER yav get version sec-01csyp6ca67vt14dsn0anbeb68 -o $PG_ADMIN_USER)
    PG_COMMON_ADMIN_USER=disk_mpfs
    PG_COMMON_ADMIN_PASSWORD=$(SUDO_USER=$SSH_USER yav get version sec-01csyp6ca67vt14dsn0anbeb68 -o $PG_COMMON_ADMIN_USER)
    SHARPEI=mpfs-sharpei.disk.yandex.net
    DBS=diskdb
    GRANTS=
else
    log "Unknown environment. Exit"
    exit 2
fi

log "Start MDBmigrate"
TMPDIR=$(mktemp -d)
log "Created tmpdir=$TMPDIR"

function clone {
    svn co svn+ssh://${SSH_USER}@arcadia-ro.yandex.ru/arc/trunk/arcadia/disk/admin/salt/pg/salt/components/pg-code/$1 ${TMPDIR}/$1
}

function list_connections {
    curl -s "http://${SHARPEI}/stat" | \
        jq -r '.[].databases[] | select(.role=="master") | "postgresql://'$PG_ADMIN_USER':'$PG_ADMIN_PASSWORD'@\(.address.host):\(.address.port)/\(.address.dbname)?sslmode=verify-full"' | \
        fgrep .db.yandex.net | fgrep -v common
}

function get_common_connection {
    curl -s "http://${SHARPEI}/get_user?uid=-1&mode=all" | \
        jq -r '.[].databases[] | select(.role=="master")| "postgresql://'$PG_COMMON_ADMIN_USER':'$PG_COMMON_ADMIN_PASSWORD'@\(.address.host):\(.address.port)/\(.address.dbname)?sslmode=verify-full"'
}

function apply_from_directory {
    for sql in ${TMPDIR}/$1/$2/*; do
        psql $3 < $sql
    done
}

for db in $DBS; do
    log "Clone $db from Arcadia"
    clone $db > /dev/null

    log "Get $db connections from sharpei"
    if [ "$db" == "diskdb" ]; then
        connections="$(list_connections)"
    else
        connections="$(get_common_connection)"
    fi
    log "Connections num: $(echo $connections | wc -w)"


    for connection in $connections; do
        host_db=$(echo $connection | awk -F'@' '{print $2}' | awk -F '?' '{print $1}')
        if [ "$CHECK_MIGRATION" == "true" ]; then
            pgmigrate --conn ${connection} --base_dir ${TMPDIR}/$db info
            continue
        fi

        log "Migrate $db on $host_db to $TARGET"
        pgmigrate --conn ${connection} --base_dir ${TMPDIR}/$db --target $TARGET migrate
        if [ "$APPLY_CODE" == "true" ]; then
            log "Apply code to $db on $host_db"
            apply_from_directory $db code "${connection}"
        fi

        if [ "$APPLY_GRANTS" == "true" ]; then
            if [ -n "$GRANTS" ]; then
                log "Apply disk grants to $db on $host_db"
                echo "$GRANTS" | psql ${connection}
            else
                log "Apply grants from directory to $db on $host_db"
                apply_from_directory $db grants "${connection}"
            fi
        fi
    done
done

log "All DBS migrated successfully"

rm -rf $TMPDIR
log "Tmpdir removed"
