#!/bin/bash

function help() {
echo
echo "$1 <command> [options]"
echo
echo "commands:"
echo
column -t -s"|" ./task.md | tail -n +3
echo
}

# Set env vars
GIT_BRANCH=$(git symbolic-ref --short -q HEAD)

function generate-passwordfile() {
    if test -z "$1"; then echo "\$1 is empty"; exit; fi
    export VAULTPASSWORD=$1
    echo "$VAULTPASSWORD" > .vault_pass
    chmod 600 .vault_pass
    echo "Password file .vault_pass created."
}

function init-venv() {
    if [ ! -d "venv$GIT_BRANCH" ]; then
        echo "Create virtualenv venv$GIT_BRANCH."
        python3 -m venv "venv$GIT_BRANCH"
    fi
}

function activate-venv() {
    echo "Source virtualenv venv$GIT_BRANCH."
    source "venv$GIT_BRANCH/bin/activate"
}

function install() {
    echo "Setup Ansible log file."
    sudo touch /var/log/ansible.log
    sudo chown $USER: /var/log/ansible.log

    init-venv
    activate-venv

    echo "Install Ansible and Python dependencies."
    sudo apt install graphviz
    pip3 install -r requirements.txt

    ansible-galaxy collection install community.general
}

function update-docs() {
    activate-venv
    python3 ./library/graph.py
    echo "Update docs success."
}

function list-hosts() {
    if test -z "$1"; then echo "\$1 is empty"; exit; fi

    activate-venv
    ansible -i $1 all --list-hosts
}

function version() {
    printf "\npython:\n"
    python --version
    printf "\npip:\n"
    pip --version

    activate-venv
    printf "\npython venv:\n"
    python --version
    printf "\npip venv:\n"
    pip --version

    printf "\nansible:\n"
    ansible --version
}

case "$1" in
    generate-passwordfile)
        generate-passwordfile $2
        ;;
    install)
        install
        ;;
    version)
        version
        ;;
    update-docs)
        update-docs
        ;;
    list-hosts)
        list-hosts $2
        ;;
    lint)
        activate-venv
        ansible-lint playbooks/*.yml
        ;;
    source)
        activate-venv
        ;;
    show-passwordless-sudo)
        echo "Enter 'sudo EDITOR=vim visudo' and append this line:"
        echo "$USERNAME ALL=(ALL) NOPASSWD: ALL"
        ;;
    *)
        help task
        exit 1
        ;;
esac