# deployfns:
# Functions for deployment scripts.
#
# Copyright (c) 2004 UK Citizens Online Democracy. All rights reserved.
# Email: francis@mysociety.org; WWW: http://www.mysociety.org/
#
# $Id: deployfns,v 1.23 2011-07-08 00:38:50 robin Exp $
#

# Warnings and errors
die () {
    echo -e "$SCRIPT_COMMAND:" "$@" 1>&2
    exit 1
}

warn () {
    echo -e "$SCRIPT_COMMAND:" "$@" 1>&2
}

_mysociety_commonlib_directory() {
    (
      unset CDPATH  # Restore cd to its default behaviour, in case the
                    # environment has a CDPATH defined.
                    # Do this in the subshell, to avoid messing with the
                    # caller’s environment.
      cd "$(dirname "${BASH_SOURCE[0]}")"/.. && pwd
    )
}
MYSOCIETY_COMMONLIB_DIR=$(_mysociety_commonlib_directory)
if [ $? -ne 0 ]
then
    # If cd or pwd failed for some reason, they will have already
    # printed an error message to stderr.
    exit $?
fi

# Reads in config file
# If $1 ends with .yml, it is loaded as YAML. Otherwise
# if there is a file named "$1.yml", then that is loaded.
# If not, the file "$1" is interpreted as a PHP file.
# $1 - config file
read_conf () {
    # XXX use of mktemp here not safe; should make a temporary directory
    CONF_SOURCE=`mktemp /tmp/ms-deploy-configsource.XXXXXX`
    
    case "$1" in
      *.yaml|*.yml)
          "$MYSOCIETY_COMMONLIB_DIR/bin/yaml2sh" --prefix=OPTION_ "$1" >$CONF_SOURCE || \
              die "shlib/deployfns read_conf: error loading config file $1"
          ;;
      *)
          if [ -f "$1.yml" ]
          then
              if [ -e "$1" ]
              then
                  die "Configuration error: both $1 and %1.yml exist (remove one)"
              fi

              "$MYSOCIETY_COMMONLIB_DIR/bin/yaml2sh" --prefix=OPTION_ "$1.yml" >$CONF_SOURCE || \
                  die "shlib/deployfns read_conf: error loading config file $1.yml"
          else
              export MYSOCIETY_CONFIG_FILE_PATH=$1
              cat << END | php >$CONF_SOURCE || \
                  die "shlib/deployfns read_conf: error calling PHP to load config file $1"
<?php
\$b = get_defined_constants();
require(getenv("MYSOCIETY_CONFIG_FILE_PATH"));
\$a = array_diff_assoc(get_defined_constants(), \$b);
foreach (\$a as \$k => \$v) {
    print \$k;
    print "=";
    print "\"\$v\"";
    print "\n";
}
?>
END
          fi
          ;;
    esac

    . $CONF_SOURCE
    rm $CONF_SOURCE
}

