#!/bin/sh

# Used by scripts/Makefile and scripts/rebar-pre-script to do a local
# install of yaws

set -e

if [ -z "$HOME" ]; then
    if [ `id -u` = 0 -a -d /root ]; then
        export HOME=/root
    else
        export HOME=/tmp
    fi
fi

script=`basename $0`
tmpgen=`mktemp /tmp/${script}.XXXXXX`

logdir="${HOME}/yaws_logs"
[ -d $logdir ] || mkdir $logdir
overwrite=true
if [ -f "${HOME}/yaws.conf" ]; then
    overwrite=false
    target="${HOME}/yaws.conf.template"
else
    target="${HOME}/yaws.conf"
fi

topdir=`cd .. && pwd`
[ -d "${VARDIR}/yaws" ] || mkdir "${VARDIR}/yaws"
[ -d "${VARDIR}/yaws/ebin" ] || mkdir "${VARDIR}/yaws/ebin"
YAWSDIR="$topdir" LOGDIR="$logdir" VARDIR="$VARDIR" PORT=8000 \
    DOCROOT="${topdir}/www" CERTDIR="${topdir}/ssl" SSLPORT=4443 \
    ./gen-yaws-conf > $tmpgen
if [ -f "$target" ] && cmp -s "$target" "$tmpgen"; then
    rm -f "$tmpgen"
else
    mv -f "$tmpgen" "$target"
    [ $overwrite = false ] && echo "--- Will not overwrite ${HOME}/yaws.conf"
    echo "--- Installing local config file at $target"
fi
if [ "$1" = true ] || [ ! -f "${HOME}/bin/yaws" ]; then
    [ -d "${HOME}/bin" ] || mkdir "${HOME}/bin"
    rm -f "${HOME}/bin/yaws"
    cp -f ../bin/yaws "${HOME}/bin/yaws"
    echo "--- Installed $HOME/bin/yaws"
fi

exit 0
