#!/bin/bash

currentCommit=$(git rev-parse HEAD)
statusFile="devUpdateStatus"

# check if branch was changed
git pull -q || exit

branches=$(scripts/getBranchesForDev)
branchesCount=$(echo "$branches" | wc -l)
count=1
conflictingBranches=0

date "+%F %X" > $statusFile
touch mergedBranches

while read -r branch; do
    branchName=$(echo $branch | cut -d"(" -f2 | cut -d")" -f1 | tr ":" "/")

    if [ $(echo $branchName | grep -c "^origin") -eq 0 ] ; then
        # remote repo
        git fetch -q $(echo $branchName | cut -f1 -d"/") 1> /dev/null
    fi

    mergeOutput=$(git merge --no-edit $branchName)

    if [ $? -ne 0 ] ; then
        echo "[$(printf "%02d" $count) / $(printf "%02d" $branchesCount)] $branch CONFLICT" >> $statusFile
        let conflictingBranches++
        git merge --abort
    fi

    let count++
done <<< "$branches"

if [ $conflictingBranches -gt 0 ] ; then
    grep -i conflict $statusFile | mail -s "[Nextcloud-Dev] $(date '+%F %X') Conflicting branches!" $1
fi

# reset to previous commit, delete all inbetween commits
git reset --hard $currentCommit