#!/bin/sh
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-

ROLE=testforge

. /usr/local/bin/usr_local_tput.bash

BASE_ROLES="base proxy"
VAR_ROLES="testforge text"
DEV_ROLES="${VAR_ROLES} testing pydev logging"
WWORK_ROLES="${DEV_ROLES}"
# LXD_ROLES="${DEV_ROLES} ansible-lxd"
# text must come before harden
HARD_ROLES="${DEV_ROLES} gpgkey harden privacy hostvms"
PEN_ROLES="${HARD_ROLES} pentest ${juju4}"
GUEST_ROLES="${HARD_ROLES} trading update"
UPD_ROLES="${PEN_ROLES} update trading winrm "
ALL_ROLES="${BASE_ROLES} ${UPD_ROLES}"

cd /o/data/TestForge/src/ansible/ || exit 1

for dir in src ; do
    grep -L 'ROLE=$' /usr/local/*$dir/*bash 2>/dev/null | \
	xargs grep -L 'ROLE=[a-z"]' 2>/dev/null | \
	xargs echo ERROR: missing in $dir
    INFO /usr/local/$dir
    for role in ${BASE_ROLES} ; do
	grep -L 'ROLE=$' /usr/local/*$dir/${role}*bash 2>/dev/null | \
	  xargs grep -L ROLE=$role  2>/dev/null | while read f; do
	    ! grep -q ROLE= "$f" && echo ROLE=$role >> "$f" && continue
	    sed -e "s/^ROLE=.*/ROLE=$role/" -i "$f"
	done
	grep -L 'ROLE=$' /usr/local/*$dir/${role}*bash 2>/dev/null | \
	    xargs grep -l ROLE=$role | while read f ; do
	    num=`ls roles/*/overlay/Linux/"$f" 2>/dev/null|wc -l|sed -e 's/ .*//'`
	    [ $num -gt 1 ] && WARN DUP $f && echo `ls roles/*/overlay/Linux/"$f" 2>/dev/null` && continue
	    [ ! -e roles/$role/overlay/Linux/"$f" ] && \
		echo cp -ip "$f" roles/$role/overlay/Linux/"$f"
	done
    done
    INFO /var/local/$dir
    grep -L 'ROLE=$' /var/local/*$dir/*bash 2>/dev/null | \
	xargs grep -L 'ROLE=[a-z"]' 2>/dev/null | \
	xargs echo ERROR: missing in $dir

    for role in ${UPD_ROLES} ; do
	grep -L 'ROLE=$' /var/local/*$dir/${role}*bash  2>/dev/null | \
	  xargs grep -L ROLE=$role 2>/dev/null | while read f; do
	    ! grep -q ROLE= "$f" && echo ROLE=$role >> "$f" && continue
	    sed -e "s/^ROLE=.*/ROLE=$role/" -i "$f"
	done
	grep -L 'ROLE=$' /var/local/*$dir/${role}*bash  2>/dev/null | \
	    xargs grep -l ROLE=$role 2>/dev/null | while read f ; do
	    num=`ls roles/*/overlay/Linux/"$f" 2>/dev/null | wc -l|sed -e 's/ .*//'`
	    [ $num -gt 1 ] && WARN DUP $f && echo `ls roles/*/overlay/Linux/"$f" 2>/dev/null` && continue
	    [ ! -e roles/$role/overlay/Linux/"$f" ] && \
		echo cp -ip "$f" roles/$role/overlay/Linux/"$f"
	done
    done
done
