#!/bin/sh

REPO="/data/repo/laravel_suse/resources/translations/content/en-us/security/"

LOCAL="/data/repo/cve-pull-work/"

cd "/data/repo"
mkdir -p "$REPO"cve

set -e

if [ -d "$LOCAL.git/" ]; then
  cd $LOCAL
  git config --local user.name $GIT_USR
  git config --local pull.rebase false
  git config -l
  git branch -v
  git fetch --all
  git checkout $REF
  git pull https://github.com/SUSE/suse-it-app-cve-content.git $REF
  git branch -v
else
  ls -ahl /data/repo
  mkdir "cve-pull-work"
  git clone https://"$GIT_USR":"$TOKEN"@github.com/SUSE/suse-it-app-cve-content.git $LOCAL
fi


RET_CODE=0

#rsync, log and backup
OUTPUT=$(rsync -ru --delete "$LOCAL"cve/ "$REPO"cve/ --log-file=/dev/stdout)

echo "OUT ::::::::"
echo "$OUTPUT"

FILES=$(echo "$OUTPUT" | grep '>f' | sed -E "s/^.*>f.+\s(.+)/\1/g")

echo "FILES :::::::::::"
echo "$FILES"

sleep 10
CNT=0
LINES=$(echo "$FILES" | wc -l)
TRIGG=$(echo "$LINES/(20+$LINES*0.1)+1" | bc)
echo $TRIGG
IFS='
'
# Disabled because of recent large updates
# for f in $FILES
# do
#   f1="https://$SUSE_HOST/security/cve/""$(basename $f)"
#   f2=${f1::-5}"/"
#   CNT=$(expr $CNT + 1)
#   if [[ $CNT -ge $TRIGG ]]; then
#     CNT=0
#     if [[ $(wget --spider --server-response $f2 2>&1 | grep '200\ OK') == '' ]]; then
#       echo "Error reaching file $f2"
#       RET_CODE=1
#     else
#       echo "File $f2 is reachable"
#     fi
#   fi
# done
#
# if [[ $RET_CODE == 1 ]]; then
#   cd "$REPO"cve
#   for f in $FILES
#   do
#     rm $f
#   done
# fi
#
# exit $RET_CODE
