#!/bin/bash

APP_DIR="/srv/www/webapps/zammad"

usage() {
    echo "$(basename "$0") rake|rails [OPTIONS]"
}

case $1 in
    rake)
        CMD="rake"
    ;;
    rails)
        CMD="rails"
    ;;
    *)
        usage
        exit 0
        ;;
esac
shift

[ -f /etc/default/zammad ] && . /etc/default/zammad

pushd $APP_DIR >/dev/null || exit

# Create writeable .irb_history for user 'zammad'
if [ ! -r .irb_history ]; then
    touch .irb_history
    chown zammad: .irb_history
    chmod u=rw,g=,o= .irb_history
fi

SUDO_ENV=(RAILS_ENV=production)
[ -n "$REDIS_URL" ] && SUDO_ENV+=(REDIS_URL="$REDIS_URL")

sudo -u zammad "${SUDO_ENV[@]}" $APP_DIR/bin/$CMD "$@"
popd >/dev/null || exit
