#!/bin/sh
LOG=/usr/local/psa/var/log/amazon
RECONFIG=/root/amazon_update_ip.conf
ADMIN_PWD=`cat /etc/psa/.psa.shadow`
ERRFILE=/tmp/amazon_update_ip.err
# check arguments
if [ -z "$2" ]; then
OLD_EXT_IP=""
NEW_EXT_IP=$1
else
OLD_EXT_IP=$1
NEW_EXT_IP=$2
fi
IPchk=`echo $NEW_EXT_IP | sed -e "s/[0-9]\{1,3\}\\\\.[0-9]\{1,3\}\\\\.[0-9]\{1,3\}\\\\.[0-9]\{1,3\}//g"`
# help
if [ -z "$1" -o "$1" = "--help" -o ! -z "$IPchk" ]; then
echo $0 [old_external_ip] new_external_ip
exit 1;
fi
date >> $LOG
echo $0 $* >> $LOG
# get old internal IP from DB
QUERY="SELECT ip_address FROM IP_Addresses;"
OLD_INT_IP=`echo $QUERY | mysql --user=admin --password=$ADMIN_PWD psa 2>$ERRFILE | tail -n 1`
if [ -s $ERRFILE ]; then
echo "Error querying database for the old IP address"
cat $ERRFILE
rm $ERRFILE
exit 2;
fi
rm -f $ERRFILE
# get new internal IP from network device
NEW_INT_IP=`/usr/local/psa/admin/sbin/ifmng -l | grep eth0 | cut -d\ -f 1`
# escape the dots to be usable in regex
OLD_INT_IP_RE=`echo $OLD_INT_IP | sed -e s/\\\\./\\\\\\\\./g`
NEW_INT_IP_RE=`echo $NEW_INT_IP | sed -e s/\\\\./\\\\\\\\./g`
# try to guess old external IP
if [ -z "$OLD_EXT_IP" ]; then
OLD_EXT_IP=`grep ^\w*MasqueradeAddress /etc/proftpd.conf | cut -d\ -f 2`
fi
# check if old IP is set
IPchk=`echo $OLD_EXT_IP | sed -e "s/[0-9]\{1,3\}\\\\.[0-9]\{1,3\}\\\\.[0-9]\{1,3\}\\\\.[0-9]\{1,3\}//g"`
if [ -z "$OLD_EXT_IP" -o ! -z "$IPchk" ]; then
echo Can\'t guess old IP or it is not defined properly as an argument
$0 --help
exit 1;
fi
echo Change IP: $OLD_INT_IP to $NEW_INT_IP and $OLD_EXT_IP to $NEW_EXT_IP
echo Change IP: $OLD_INT_IP to $NEW_INT_IP and $OLD_EXT_IP to $NEW_EXT_IP >> $LOG
# Make a backup
cp /etc/hosts /etc/hosts.tmp
ERR=$?
# If backup fails, there is a problem
if [ $ERR -ne 0 ]; then
echo ERROR making a backup copy of /etc/hosts to /etc/hosts.tmp
exit 2;
fi
sed -e s/$OLD_INT_IP_RE/$NEW_INT_IP_RE/g < /etc/hosts.tmp > /etc/hosts
# create reconfigurator config
rm -f $RECONFIG.{old,new}
/usr/local/psa/bin/reconfigurator $RECONFIG.old
# map OLD_INT_IP -> NEW_INT_IP
if [ "$OLD_INT_IP" != "$NEW_INT_IP" ]; then
sed -e s/\>\ eth0\ $OLD_INT_IP_RE/\>\ eth0\ $NEW_INT_IP_RE/g < $RECONFIG.old > $RECONFIG.new;
else
cp $RECONFIG.old $RECONFIG.new;
fi
# map OLD_EXT_IP -> NEW_EXT_IP
if [ "$OLD_EXT_IP" != "$NEW_EXT_IP" ]; then
echo xxx $OLD_EXT_IP 255.255.255.0 -\> xxx $NEW_EXT_IP 255.255.255.0 >> $RECONFIG.new;
fi
# do the actual work
/usr/local/psa/bin/reconfigurator $RECONFIG.new
/usr/local/psa/bin/amazon_setup_ip $NEW_EXT_IP
rm -f $RECONFIG.{old,new} $ERRFILE