#!/bin/sh -e

#
# This script writes the ip address of the machine it is running on
# to a config.php file into the ownCloud config directory.
#
# The config dir has to be passed as the first argument of the script.
#
# Klaas Freitag <freitag@owncloud.com>, Copyright ownCloud Inc.
#
if [ -e /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
fi

# Let's ignore meta entries (ifup -a)
if [ "$ADDRFAM" = "meta" ]; then
    exit 0
fi

# Grep the previous IP address
if [ -e /var/run/owncloud.ip ]; then
    previous_ip=`cat /var/run/owncloud.ip`
fi

# read config from either the first argument the script is called with,
# or from the owncloud default config dir.
ocConfigDir=${1:-/var/www/owncloud/config}
# lo emission handled by /etc/init/network-interface.conf
if [ "$IFACE" != lo ]; then
    ip=`/sbin/ifconfig|grep inet|head -1|sed 's/\:/ /'|awk '{print $3}'`
    hn=`hostname`
    cfg=$ocConfigDir/oc_trusted_domain.config.php
    cat >${cfg} <<EOF
<?php

  if(php_sapi_name() !== 'cli') {
     \$CONFIG = array (
         'trusted_domains' => array( 0 => '$ip',
                                     1 => '$hn',
     ),
  );
  }
EOF
   chown www-data.www-data ${cfg}
   chmod 640 ${cfg}

   # write the run-file containing the current ip
   echo $ip > /var/run/owncloud.ip

   if [ "$ip" != "$previous_ip" ]; then
        log_success_msg "Creating new self signed certificate"
        gen_self_signed_cert /usr/share/openssl/oc_appliance.cnf.tmpl
        service apache2 restart
   fi
   log_success_msg "ownCloud: Registered ip $ip/$hn as trusted domain."

fi
