#!/bin/bash
# -*- indent-with-tabs: 0 -*-

version=0.10
program=${0##*/}
progdir=${0%/*}
if [ "$progdir" = "$program" ]; then progdir="."; fi

# ----------------------------------------------------------------------
function usage() {
# Possible sections:
#     NAME
#     SYNOPSIS
#     CONFIGURATION      [Normally only in Section 4]
#     DESCRIPTION
#     OPTIONS            [Normally only in Sections 1, 8]
#     EXIT STATUS        [Normally only in Sections 1, 8]
#     RETURN VALUE       [Normally only in Sections 2, 3]
#     ERRORS             [Typically only in Sections 2, 3]
#     ENVIRONMENT
#     FILES
#     VERSIONS           [Normally only in Sections 2, 3]
#     CONFORMING TO
#     NOTES
#     BUGS
#     EXAMPLE
#     SEE ALSO

    cat <<EOF
NAME
        $program - set up buildbot workers

SYNOPSIS
        $program [OPTIONS]

DESCRIPTION

        Set up environment and buildbot worker files after checking
        out the buildbot directory tree from the repository.

EOF
    echo -e "OPTIONS"
    if   [ "$(uname)" = "Linux" ]; then
        egrep "^[       ]+[-][A-Za-z| -]+\*?\)[ ]+[A-Za-z].+#" $0 | tr -s "\t|" "\t," | sed -r -e 's/\)[ \t]+([A-Z]+)=\$2[^#]*#/=\1\t/' -e 's/\)[^#]*#/\t/'
    else
        egrep "^[       ]+[-][A-Za-z| -]+\*?\)[ ]+[A-Za-z].+#" $0 | sed 's/\|.*\$2[^#]*#/       /'| sed -E 's/\|.*\)[^#]*#/     /'
    fi
    cat <<EOF

AUTHOR
        Written by Henrik Levkowetz, <henrik@levkowetz.com>. Repository:
        https://svn.tools.ietf.org/svn/tools/ietfdb/trunk/buildbot

COPYRIGHT
        Copyright 2020 the IETF Trust. All rights reserved.

        Redistribution and use in source and binary forms, with or
        without modification, are permitted provided that the conditions
        laid out in the 3-clause BSD license is followed.

        License text: https://opensource.org/licenses/BSD-3-Clause

EOF

}

# ----------------------------------------------------------------------

function die() {
    echo -e "\n$program: error: $*" >&2
    exit 1
}

function err() {
    echo -e "${red}$*${reset}" >&2
}

function note() { 
        if [ -n "$VERBOSE" ]; then echo -e "\n$*"; fi
}

# ----------------------------------------------------------------------
function version() {
        echo -e "$program $version"
}

# ----------------------------------------------------------------------
trap 'echo "$program($LINENO): Command failed with error code $? ([$$] $0 $*)"; exit 1' ERR


# ----------------------------------------------------------------------
# Option parsing

# Options
shortopts=a:hp:s:vV
longopts=admin:,help,server:,passwd:,python:,verbose,version

# Default values
read -d ' ' <<< $(who -m)
user=$REPLY
name=$(getent passwd $user | cut -d ':' -f 5 | cut -d ',' -f 1)
server='zinfandel.tools.ietf.org'
pass=''                                 # must be set on the command line
python=python3.6

if   [ "$(uname)" = "Linux" ]; then
    args=$(getopt -o "$shortopts" --long "$longopts" -n '$program' -- $SV "$@")
    if [ $? != 0 ] ; then die "Terminating..." >&2 ; exit 1 ; fi
    files="$@"
    eval set -- "$args"
    sed="sed -r"
else
    # Darwin, BSDs
    args=$(getopt -o$shortopts $SV $*)
    if [ $? != 0 ] ; then die "Terminating..." >&2 ; exit 1 ; fi
    files="$@"
    set -- $args
    sed="sed -E"
fi

while true ; do
    case "$1" in
        -a| --admin)    admin="$2"; shift;;     # "Name <email>" of buildbot admin
        -h| --help)     usage; exit;;           # Show this help, then exit
        -p| --passwd)   pass=$2; shift;;        # Worker password
        --python)       python=$2; shift;;      # Python version to use (e.g., 'python3.6')
        -s| --server)   server=$2; shift;;      # Set the server fqdn
        -v| --verbose)  VERBOSE=1;;             # Be more talkative
        -V| --version)  version; exit;;         # Show program version, then exit
        --)             shift; break;;
        *) die "Internal error, inconsistent option specification: '$1'";;
    esac
    shift
done

# ----------------------------------------------------------------------
# The program itself

dir=$(dirname $(realpath $0))
if [ -d "$dir/slaves" ]; then
    path="$dir/slaves"
else
    path="$dir/workers"
fi

for worker in $path/*; do
    (
        cd $worker;
        pwd
        if [ ! -d ./env ]; then
            echo "Setting up virtual environment"
            # Change python version to match deployment version
            python3.6 -m venv env
        fi
        . env/bin/activate
        pip install buildbot-worker
        if [ ! -f ./buildbot.tac ]; then
            pwfile=$dir/${worker##*/}_pw
            echo "Looking for pwfile: $pwfile"
            [ -f "$pwfile" ] && pass=$(< $pwfile)
            [ -z "$pass" ] && die "Missing parameter: worker password"
            buildbot-worker create-worker $PWD $server ${PWD##*/} $pass
        fi
        if ! grep -q "$name" ./info/admin; then
            read -p "Expected $name in $PWD/info/admin, but found $(<./info/admin) -- change it [Y/n]?"
            if [ "$REPLY" = "Y" -o "$REPLY" = "y" ]; then
                if [ -z "$admin" ]; then
                    read -p "Admin (Your Name <your@email.example>): "
                    admin=$REPLY
                fi
                echo "Setting up ./info/admin"
                echo "$admin" > ./info/admin
                echo "Setting up ./info/host"
                echo "$(uname -s -n -r) $(python --version)" > ./info/host
            fi
        fi
        buildbot-worker stop
        buildbot-worker start
    )
done