#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.



inherit default os envinfo;
include "$passwd_module_inherit";
include output cartridge-common decrypt-passwd;
inherit extendperm;

DESCRIPTION="JEM Password Manager module";
VERSION="1";
DEFAULT_ACTION="Usage";

$PROGRAM 'chpasswd';
$PROGRAM 'grep';


function doUsage() {
    showUsageMessage;
}

function preSetCallback(){
    local res=0
    decryptPassword $@
    res=$?
    [ $res -eq 0 ] || die -q
}

function doSet(){
	set -- ${JEM_PARAMS[@]}
	[ "x${COMPUTE_TYPE}" == "xcartridge" ] &&  restoreEnvironmentVariables && {
            export J_OPENSHIFT_APP_ADM_USER=$Admin_App_User;
            [ -f "${CARTRIDGE_HOME}/jelastic/scripts/reset_password.sh" ] && source "${CARTRIDGE_HOME}/jelastic/scripts/reset_password.sh";
            while [ "$1" != "" ];
            do
            case $1 in
                 -p )       shift
                  J_OPENSHIFT_APP_ADM_PASSWORD=$1 ;;
              esac
              shift
            done
            _setPassword > /dev/null 2>&1; local res=$?;
            export J_OPENSHIFT_APP_ADM_USER=${J_OPENSHIFT_APP_ADM_USER}; 
            #saveEnvironmentVariables;
            [ $res -eq 0 ] && writeJSONResponseOut "result=>0" "message=>Password set successfully" "username=>$J_OPENSHIFT_APP_ADM_USER" || { writeJSONResponseErr "result=>4051" "message=>Could not set password!"; return 1; };
            #
            #  Parsing of argument is implemented inside module to avoid extra work for enduser in hook
            #
            return $res;
	} ;

	if echo $@ | $GREP -qP "\-u"
	then
		setPassword $@ && writeJSONResponseOut "result=>0" "message=>Password set successfully" || { writeJSONResponseErr "result=>4051" "message=>Could not set password!"; return 1; };
	else
		setPassword -u "$default_user" $@ && writeJSONResponseOut "result=>0" "message=>Password set successfully" || { writeJSONResponseErr "result=>4051" "message=>Could not set password!"; return 1; };
	fi
}

function postSetCallback(){
    ExtendPerm ;
}

function preSetosCallback(){
    local res=0
    decryptPassword $@
    res=$?
    [ $res -eq 0 ] || die -q
}

function doSetos(){
	set -- ${JEM_PARAMS[@]}
		while [ "$1" != "" ];
		do
		  case $1 in
		    -u )       shift
		      local user=$1
		      ;;
		    -p )       shift
		      local password=$1
		      ;;
                    -d )       shift
                      local homeDirectory=$1
                      ;;
		  esac
		  shift
		done
		[ -f /etc/vsftpd/vsftpd.conf.tpl ] && cp -f /etc/vsftpd/vsftpd.conf.tpl /etc/vsftpd/vsftpd.conf || true;
                [ -z "$password" ] && { writeJSONResponseErr "result=>4099" "message=>Missing param" ; return 99; }
                if [ "$user" == "jelastic-ftp" -a -d "/etc/vsftpd/" ]; then
                        include vsftpd;
                        setvsFtpCert;
                else
                        [ -z "$homeDirectory" ] && { writeJSONResponseErr "result=>4099" "message=>Missing param" ; return 99; }
                        /usr/bin/mkdir -p $homeDirectory
                        if ! $GREP -q "^${user}:" /etc/passwd ; then
                            /usr/sbin/adduser --home-dir $homeDirectory --shell /bin/false $user 2>/dev/null;
                        fi
                        /usr/bin/chown -R $user:$user $homeDirectory
                fi

 		echo "$user:$password" | $CHPASSWD > /dev/null 2>&1 && writeJSONResponseOut "result=>0" "message=>Password set successfully" || { writeJSONResponseErr "result=>4051" "message=>Could not set password!"; return 1; };

}

function postSetosCallback() {
    [ -n "$FIREWALL_ENABLED" -a "${FIREWALL_ENABLED+xxx}" = "xxx" ] && [ "${FIREWALL_ENABLED}" -eq "1" ] && {
        local msg=$(doAction "firewall" "Start");
    }
    return 0;
}

function describeSet() {
    echo "Set password for selected user";
}

function describeSetParameters() {
    echo "-p <password> [-u <user>]";
}

function describeSetOptions() {
    echo "-p: password";
    echo "-u: user name";
}

function describeSetos() {
    echo "Set password";
}

function describeSetosParameters() {
    echo "-p <password> -u <user>";
}

function describeSetosOptions() {
    echo "-p: new password";
    echo "-u: user name";
}
