#!/bin/sh
# __nextcloud/explorer/password

# Checks if the given password is working by hacking somehow into the nextcloud
# php libary.
#
# Outputs:
#  - "noop" if no password given as parameter
#  - "matched" if the given parameter matched the password
#  - "mismatched" if the given parameter did not matched
#  - "" if no nextcloud directory could be detected


# Check if the password exists, else this is nonsense
password="$__object/parameter/password"
if [ -f "$password" ]; then
    password="$(cat "$password")"
else
    # no password to compare - it's managed by someone other
    echo noop
    exit
fi

# Get parameters
user="$__object/parameter/user"
if [ -f "$user" ]; then
    user="$(cat "$user")"
else
    user="$__object_id"
fi
cloud="$(cat "$__object/parameter/cloud")"
www_user="$(cat "$__object/parameter/www-user")"



# Check if there exists the installation
if [ -d "$cloud" ]; then
    # if those files exist, everything should be good
    if [ -f "$cloud/occ" ] && [ -f "$cloud/config/config.php" ]; then
        # Output the information from the custom php
        # change the user to be on the safe side if something is written
        su -s /bin/sh -l "$www_user" -- -e <<SU
cd '$cloud'
pw='$password' \
php -r 'define("OC_CONSOLE",1); require_once(__DIR__."/lib/base.php");
        print(\\OC::\$server->getUserSession()->getManager()->checkPasswordNoLogging("$user", getenv("pw")) ? "matched" : "mismatched");'
SU
    fi
fi
