#!/bin/bash
# ===========================================================================

# Copyright (c) 2015 Eclipse Foundation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#    Théodore Biadala (Eclipse Foundation)
# ===========================================================================

# THIS IS A WORK IN PROGRESS WHICH DO NOT CURRENTLY WORK.

LOCKFILE=/tmp/update-d10-database-update
if [ ! -f $LOCKFILE ]; then
  touch $LOCKFILE;
  if [ $# -ne 0 ]; then

    # Define the accepted values
    accepted_websites=("newsroom" "blogs" "marketplace" "projects" "accounts" "threadxalliance")

    not_accepted=true
    for value in "${accepted_websites[@]}"; do
        if [ "$1" == "$value" ]; then
            not_accepted=false
            break
        fi
    done

    if $not_accepted; then
      echo "Please enter a valid website."
      exit
    fi

    HOST="mysql-read.eclipse.org"
    USER="drupal_$1_ro"
    REMOTE_PROXY="bastion"
    REMOTE_HOSTNAME="api-vm1"
    RESULT_FILE="dev_drupal_$1"
    DATABASE="drupal_$1"

    # Make sure the user specified a valid web site to build.
    if [ -z ${REMOTE_PROXY+x} ]; then
      echo "You must enter a valid site name in order for this command to work. Try viewing the contents of this file with an editor"
      exit
    fi

    #read -p "Enter the Host: " HOST
    #echo    # Print a newline after the user input
    #read -p "Enter the database: " DATABASE
    #echo    # Print a newline after the user input
    #read -p "Enter the User: " USER
    #echo    # Print a newline after the user input
    read -s -p "Enter Password for read only user: " PASSWORD
    echo    # Print a newline after the user input
    echo "Running SQL Dump from $REMOTE_PROXY server..."
    COMMAND="mysqldump -u $USER -p$PASSWORD -h $HOST $DATABASE --no-autocommit --single-transaction --opt -Q --column-statistics=0 | gzip > ~/sql/$RESULT_FILE.sql.gz"
    ssh $REMOTE_PROXY $COMMAND
    scp $REMOTE_PROXY:sql/"$RESULT_FILE".sql.gz /tmp
    scp /tmp/"$RESULT_FILE".sql.gz $REMOTE_HOSTNAME:webdev/sql/
    echo "Done"

    rm $LOCKFILE

  else
    echo "USAGE: ./update-drupal10-db.sh SITENAME"
  fi
else
  echo "Another job is running.  Check the existence of $LOCKFILE"
  exit
fi




