#!/bin/bash

ROOT_PATH=$(dirname "$0") 

[ -r "$ROOT_PATH/env"] && . "$ROOT_PATH/env" 
RUN_WORD="${RUN_WORD:-RUN:}"
TIME_OUT=${TIME_OUT:-20}
DEVADM_USER=${DEVADM_USER:-devadm}
WEBHOOK_RUN=${WEBHOOK_RUN:-/usr/local/bin/on_webhook_provisioning}

DATA=$1
REPO_SSH_URL=$(echo "$1" | jq -r ".repository.ssh_url")
REPO_FULLNAME=$(echo "$1" | jq -r ".repository.full_name")
COMMIT_0_MESSAGE=$(echo "$1" | jq -r ".commits[0].message")
COMMIT_MODIFIED=$(echo "$1" | jq -r ".commits[].modified[]")
COMMIT_AUTHOR_EMAIL=$(echo "$1" | jq -r ".commits[].author.email")
RUN_COMMIT_MSG="$(echo $COMMIT_0_MESSAGE | awk -F"RUN:" '{ print $2 } ')"

[ -n "$DEVADM_USER" ] && [ -n "$WEBHOOK_RUN" ] && [ -n "$REPO_SSH_URL" ] && 
WK_RUN=/tmp/env_webhook_provisioning.$$

echo "
REPO_SSH_URL=\"$REPO_SSH_URL\"
REPO_FULLNAME=\"$REPO_FULLNAME\"
COMMIT_AUTHOR_EMAIL=\"$COMMIT_AUTHOR_EMAIL\"
RUN_COMMIT_MSG=\"$RUN_COMMIT_MSG\"
RUN_COMMIT_MODIFIED=\"$COMMIT_MODIFIED\"  
"> "$WK_RUN"

sudo -u "$DEVADM_USER" "$WEBHOOK_RUN" "$WK_RUN" && rm -f "$WK_RUN"
