#!/bin/bash

# Get Hostname of server to be migrated
read -p "hostname? (e.g., box3000.bluehost.com) " HOSTNAME;

# Get box#
HOST=$(echo $HOSTNAME | cut -d. -f1); 

# Get sererid for hostname within database
SERVERID=$(mysql -D backups -e "select serverid from server where hostname='$HOSTNAME';" | grep ^[0-9]); 

# Confirm update
echo; echo "Update $HOSTNAME in backups database.."; echo; 
read -p "Are you sure you want to update entries for $HOSTNAME? (y/n) " ANS;

# Remove previous backup entries for hostname if answer = y, otherwise exit script
if [ "$ANS" == "y" ];
    then
	mysql -D backups -e "delete from backupstate where hostname='$HOSTNAME' limit 1"; 
	mysql -D backups -e "delete from backupstatepartitions where hostname='$HOSTNAME' limit 1"; 
	mysql -D backups -e "delete from iscsimounts where plabel like '$HOST%'"; 
	mysql -D backups -e "delete from pubkeys where serverid='$SERVERID' limit 1"; 
	echo; echo "Successfully removed old backup server entries for $HOSTNAME within the backups database"; echo;
    else
	echo "Doing nothing.."; echo;
	exit 1;
fi;

# Get IP within backups database and hostname's public IP
BIP=$(mysql -D backups -e "select INET_NTOA(backnetip) from newbacknetip where serverid='$SERVERID'" | grep ^[0-9]);
IP=$(dig A $HOSTNAME +short)

# If no A record is found using dig, user will be prompted to manually input
if [ -z "$IP" ];
    then
	echo "IP for $HOSTNAME not found using dig!"; echo;
	read -e -p "What is the public IP for $HOSTNAME? (i.e., 50.116.71.161) " IP; echo;
fi;

# If IP within backups db is not the hostname's public IP, update it
if [ "$BIP" != "$IP" ]; then
	mysql -D backups -e "update newbacknetip set backnetip = INET_ATON('$IP') where serverid='$SERVERID'";
	echo; echo "Updated database entry for old IP from $BIP TO $IP"; echo;
fi;

echo; echo "Run \`/var/www/bin/addbackup.mass\` to update the backup server for $HOSTNAME"; echo; 
