#!/bin/bash
#############################################################
# Name:        Supportconfig Plugin for Salt
# Description: List Salt jobs
# License:     GPLv2
# Author:      Bo Maryniuk <bo@suse.de>
# Written:     2016 Oct 28
#############################################################

SVER=0.1.0
OF="plugin-saltconfiguration.txt"

for RCFILE in $(ls /usr/lib/supportconfig/resources/*.rc); do
    [ -s $RCFILE ] && . $RCFILE || { echo "ERROR: Initializing resource file: $RCFILE"; exit 1; }
done

#
# Get Salt config file.
# Remove all the comments via parsing it.
#
function get_salt_config() {
    cnf=$1
    if /usr/lib/venv-salt-minion/bin/python3 -c "import yaml" 2>1; then
        PYTHON=/usr/lib/venv-salt-minion/bin/python3
    elif python3 -c "import yaml" 2>1; then
        PYTHON=python3
    elif python -c "import yaml" 2>1; then
        PYTHON=python
    elif python2 -c "import yaml" 2>1; then
        PYTHON=python2
    else
        echo "Please install yaml for python."
        return
    fi

    OUTPUT=$($PYTHON -c "import yaml;print(yaml.dump(yaml.safe_load(open('$cnf')) or 'N/A', default_flow_style=False))")

    # Remove possible passwords
    echo "$OUTPUT" | sed -e 's/\(.*pass:\).*/\1 *REMOVED BY SUPPORTCONFIG*/g;s/\(.*password:\).*/\1 *REMOVED BY SUPPORTCONFIG*/g'
}

check_packages "salt" || check_packages_failhard "venv-salt-minion"
log_entry $OF "Supportconfig Plugin for SaltStack, v${SVER}"

for cfg_file in $(ls /etc/salt/* /etc/salt/*.d/*conf /etc/venv-salt-minion/* /etc/venv-salt-minion/*.d/*conf); do
    if [ -f $cfg_file ]; then
	echo "Content of the config: $cfg_file"
	echo "--------------------------------"
	get_salt_config $cfg_file
	echo -e "--------------------------------\n"
    fi
done
