#!/usr/bin/env bash
# Shortcut for running ownClouds `occ` command when not logged in as {{ owncloud__app_user }} user and sudo allows it.
# https://doc.owncloud.org/server/9.0/admin_manual/configuration_server/occ_command.html

# {{ ansible_managed }}

set -o nounset -o pipefail -o errexit

# Environment variable `OC_PASS` is striped normally by `sudo`.
# `--preserve-env` would preserve all environment variables.
# This should be OK for this command.
# It seems to be impossible to set "env_keep" via the command line?
# Other possibility would be to configure it properly via Defaults!{{ owncloud__app_home }}/occ env_keep=OC_PASS


# The occ command should be invoked with PWD set to `owncloud__app_home` to avoid occ not finding it’s DB spec:
# https://github.com/owncloud/core/issues/17583
# It is fixed in 8.2 but lets call `occ` like the documentation suggests it:
# https://doc.owncloud.org/server/9.0/admin_manual/configuration_server/occ_command.html?highlight=occ#using-the-occ-command
cd '{{ owncloud__app_home }}' || exit 1

# Long command line options seem to be not supported as of 1.8.3 in Ubuntu precise.
# sudo --preserve-env --user '{{ owncloud__app_user }}' php --file '{{ owncloud__app_home }}/occ' "$@"
# {#
# Example cron entry:
# - name: 'owncloud-some-job'
#   cron_file: 'owncloud-something'
#   minute: 23
#   hour: 05
#   job: 'USER={{ owncloud__app_user | quote }} {{ some_script | quote }}'
#   user: '{{ owncloud__app_user }}'
#
#}

if [ "$USER" == '{{ owncloud__app_user }}' ]
then
    php --file '{{ owncloud__app_home }}/occ' "$@"
else
    sudo -E -u '{{ owncloud__app_user }}' php --file '{{ owncloud__app_home }}/occ' "$@"
fi
