#!/bin/sh -ex

# This script installs and starts the mapping service on Debian Lenny.
## Please take care to make this script idempotent, i.e. running it 
## again should not change anything.

umask 002

DEST=${DEST:-/srv/osm}
ME=map

mkdir -p "$DEST/$ME" "$DEST"/git
cd "$(dirname "$0")"/..
SRC=$(/bin/pwd)
export GIT_DIR="$DEST"/git/$ME.git
if test ! -d "$GIT_DIR" ; then
    cp -a .git "$GIT_DIR"
    cp doc/update_git "$GIT_DIR"/hooks/update
    chmod +x "$GIT_DIR"/hooks/update
    cd "$DEST/$ME"
    git checkout -f -b web
else
    cd "$DEST/$ME"
fi

# minimal packages required
apt-get update
apt-get -y install nginx php5-fpm locales

## errors go to syslog
cat <<END >/etc/php5/fpm/conf.d/99-errors.ini
;; auto-generated by "$PWD/doc/$(basename "$0")"
error_log = syslog
END
sed \
    -e 's,^;*error_log *=.*,error_log = syslog,' \
    -i /etc/php5/fpm/php-fpm.conf

# tell nginx what to do
sed \
    -e "s,%HOSTNAME%,$(hostname -f),g" \
    -e "s,%ME%,$ME,g" \
    -e "s,%DEST%,$DEST,g" \
    < $SRC/doc/nginx.conf > /etc/nginx/sites-available/map.openseamap.conf
cd /etc/nginx/sites-enabled
ln -sf ../sites-available/map.openseamap.conf .

# (re)start services
systemctl enable php5-fpm.service 
systemctl restart php5-fpm.service

systemctl enable nginx.service
systemctl restart nginx.service

if test ! -s /etc/sudoers.d/openseamap ; then
    echo "You might want to enable this entry in /etc/sudoers.d/openseamap:"
    echo ""
    echo "# %openseamap   ALL=(ALL:ALL) NOPASSWD: ALL" >/etc/sudoers.d/openseamap
    cat /etc/sudoers.d/openseamap
fi
