#!/bin/sh

onlystatic="yes"

if [ $# -ge 1 ]; then
    onlystatic=""
fi

set -e

update_repo() {
    repo=$1
    echo $repo
    cd $repo

    case $repo in
        ~/.password-store)
            git checkout master
            git add .
            git commit -m "updated by $0"  || true
            git pull
            git checkout nico-privat
            ;;
        ~/vcs/cdist-workdir)
            mr update
            ;;
    esac

    git add .
    git commit -m "updated by $0 on $(hostname)"  || true
    git pull
    git push

}

REPOLIST="$HOME/.ctt $HOME/bin $HOME/vcs/notes $HOME/vcs/nico-dot-cdist $HOME/vcs/cdist-workdir/dot-cdist $HOME/vcs/ansible-main"
REPOLIST2="$REPOLIST $HOME/.password-store"

# First in parallel, then en sequence to spot errors
for repo in ${REPOLIST}; do ( update_repo $repo & ) ; done

echo "Waiting for async process to finish ..."
wait
exit 0

echo "Starting for sync process ..."

for repo in ${REPOLIST}; do update_repo $repo ; done

# Repos we want to sync, but don't want to update the working tree
for repo in \
    ~/vcs/k8s-config/ \
    ~/vcs/ansible-main/ \
    ; do
    echo $repo
    cd $repo
    git pull
    git push
done

# Step 2: pull/push all other repos in ~/vcs/
# We cannot commit as we do not know the state, but we
# can ensure everything committed before is pushed out

if [ $onlystatic ]; then
    exit 0
fi

set +e

for repo in ~/vcs/*; do
    echo "$repo"
    cd ${repo}
    git pull
    git push
done