#! /bin/bash 
NEWIP=$1

if [[ $UID != 0 ]]; then
    echo "Please run this script with sudo:"
    echo "sudo $0 $*"
    exit 1
fi

#FIXME(Ariel): Make these variables replaceable from config.sh
GEONODE_ETC=/etc/starterkit
GEOSERVER_DATA_DIR=/usr/share/geoserver/data
APACHE_SERVICE="invoke-rc.d apache2"

# Replace SITEURL in $GEONODE_ETC/local_settings.py
echo "Replacing SITEURL in $GEONODE_ETC/local_settings.py"
perl -pi -e 's/SITEURL =(.*)/SITEURL = "replaceiphere"/g' $GEONODE_ETC/local_settings.py
sed -i "s#replaceiphere#http://$NEWIP/#g" $GEONODE_ETC/local_settings.py

echo "Adding entry for local ip in $GEOSERVER_DATA_DIR/printing/config.yaml"
printing_config=$GEOSERVER_DATA_DIR/printing/config.yaml

if grep -q "$NEWIP" "$printing_config"
then
    echo '  IP was already added to the printing whitelist.'
else
    sed -i "s#hosts:#hosts:\n  - !ipMatch\n    ip: $NEWIP#g" $printing_config
fi

if grep -q "^ALLOWED_HOSTS" "$GEONODE_ETC/local_settings.py"
then
    echo "Replacing ALLOWED_HOSTS in $GEONODE_ETC/local_settings.py"
    perl -pi -e 's/^ALLOWED_HOSTS(.*)/ALLOWED_HOSTS=["replaceiphere", "localhost"]/g' $GEONODE_ETC/local_settings.py
    sed -i "s#replaceiphere#$NEWIP#g" $GEONODE_ETC/local_settings.py
else
    echo "Adding ALLOWED_HOSTS in $GEONODE_ETC/local_settings.py"
    echo "ALLOWED_HOSTS=['"$NEWIP"', 'localhost']" >> $GEONODE_ETC/local_settings.py
fi

sk fixsitename

# Restart apache server
$APACHE_SERVICE restart

# Run updatelayers
sk updatelayers

# Run updatemaplayerip
sk updatemaplayerip
