#!/bin/bash
#
##############################
## somenet.org ansible tool ##
##############################
# Part of: https://git.somenet.org/root/pub/somesible.git
# 2017-2026 by someone <someone@somenet.org>
#
# first-run-pre-requirements:
## git.somenet.org access to somesible repo.
### (presumably: /root/pub/somesible)
#
# does:
## get paths
## update somesible directory/git-submodule (clone and call update.sh)
## rsync over diversions
## cleanup
## run ansible process
#

SOMESIBLE_OLDPWD=$(pwd)
SOMESIBLE_PWD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $SOMESIBLE_PWD

if [ -e "update_somesible.sh" ]; then
  echo "*** ERROR (run_somesible.sh): this is not supposed to be run inside the somesible git repo. abort."
  exit 1
fi

# (try to) read config in parent dir.
if [ -e "somesible.conf" ]; then
    . "somesible.conf"
fi


# delete old lock-file, if too old, allowing to run the update.
find "/tmp/run_somesible_${USER}.sh.lock" -mmin +60 -delete >/dev/null 2>&1
if [ -e "/tmp/run_somesible_${USER}.sh.lock" ]; then
  echo "*** EARLY EXIT: /tmp/run_somesible_${USER}.sh.lock is too new"
  echo 'maybe need to: rm -f "/tmp/run_somesible_${USER}.sh.lock"'
  exit 0
fi

###################################
# update or clone and reset repos #
###################################
git config fetch.recurseSubmodules false

if [ ! -e "$SOMESIBLE_PWD/somesible/.git" ]; then
  echo "*** WARN (run_somesible.sh): somesible git repo not found. cloning..."
  git clone git@git.somenet.org:/root/pub/somesible somesible
fi

cd $SOMESIBLE_PWD/somesible || { echo "*** ERROR (run_somesible.sh): Tried to get a clone of somesible, but it still does not exist. Aborting. ***"; exit 1;}
# allow to skip updating.
if [ -z "$SOMESIBLE_SKIP_UPDATE" ]; then
    #(nohup sh ./update_somesible.sh </dev/null >>/dev/null 2>&1)
    sh ./update_somesible.sh

    rsync -qclDP "${SOMESIBLE_PWD}/somesible/run_somesible.sh" "${SOMESIBLE_PWD}/"
fi
cd $SOMESIBLE_PWD


#########################
# rsync over diversions #
#########################
mkdir -p "${SOMESIBLE_PWD}/override/"
rsync -qcrlDP "${SOMESIBLE_PWD}/override/" "${SOMESIBLE_PWD}/somesible/"


###############
# run ansible #
###############
cd $SOMESIBLE_PWD/somesible

# currently its not possible to have conditional playbook includes.
# hack them in...
if [ -e "${SOMESIBLE_PWD}/site.yml" ]; then
  ansible-playbook site_parent.yml -l managed "$@"
else
  ansible-playbook site_base.yml -l managed "$@"
fi

# release lock
rm -f "/tmp/run_somesible_${USER}.sh.lock"
