#!/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.


[ -n "${UNINTERRACTLIB_VERSION:-}" ] && return 0;
UNINTERRACTLIB_VERSION="0.1";

inherit os;
include output;

$PROGRAM 'expect';
$PROGRAM 'grep';

function runNonInterractive(){
        echo -n $(date +%D.%k:%M:%S.%N ) >> "$VCS_UPDATE_LOG" 2>&1;
        F_ERR_HANDLER="/tmp/ERR_HANDLER.tmp";
        command="$@"
        $EXPECT -c "eval spawn \"$command\" ; expect -timeout 60 -re U { send \r } ; expect -timeout 60 -re "Pass" { send \r }  ; interact;" | tee -a $VCS_UPDATE_LOG > $F_ERR_HANDLER  2>/dev/null || $EXPECT -c "eval spawn $command >> $VCS_UPDATE_LOG ; " | tee -a $VCS_UPDATE_LOG > $F_ERR_HANDLER  2>/dev/null;
        [ -f $F_ERR_HANDLER ] && ERR_HANDLER=$(<$F_ERR_HANDLER) && rm $F_ERR_HANDLER;
        if [[ $ERR_HANDLER == *fatal:* || $ERR_HANDLER == *error:* ]]; then 
            echo "NodeId - $(hostname|awk -F - {'print $1'}|grep -o [0-9]*); Host - $(hostname); URL - $URL; Directory - ${WEBROOT}/${PROJECT_NAME}; " >> $ACTIONS_LOG
            if [ ${COMPUTE_TYPE} == "apache-ruby" -o ${COMPUTE_TYPE} == "nginx-ruby" ] ; then 
                [ ! -d "${WEBROOT}/${PROJECT_NAME}/" ] && mkdir -p "${WEBROOT}/${PROJECT_NAME}/" 1>/dev/null 2>&1 ; # TODO: add git url validation
                updateOwnership "${WEBROOT}/${PROJECT_NAME}";
            fi
            if [[ $ERR_HANDLER =~ "personal access token instead" ]]; then 
                echo "$ERR_HANDLER" | sed "s/$AUTH@//" >> $ACTIONS_LOG 2>/dev/null;
                return 2;
            else
                echo "$ERR_HANDLER" | sed "s/$AUTH@//" |  grep -i -v "Password" >> $ACTIONS_LOG 2>/dev/null;
            return 1;
            fi
        else
            return 0; 
        fi
        ##### laster need to be moved to git.lib
}
