#!/bin/bash
# minimal config version
MIN_VERSION="3.0"

CFG=/etc/notamock.cfg
CFGD=/etc/notamock.d

# special config for project
if [ -f './notamock.cfg' ] ; then
    CFG=$(realpath ./notamock.cfg)
    CFGD=''
fi

PLATFORM=$(rpm --eval %distro_release)
VARIABLES=''
BUILD_args=''
WATCH_LINES=5
PARALLEL=${PARALLEL:-1}
BUILDER_NAME=${BUILDER_NAME:-$(hostname)}
VERBOSE=yes
DNFCACHE="/tmp/dnfcache"

HLP(){
echo "$0 - script to start abf builders (builder-c) in notamockd containers"
echo "
=======================================================================
Warning! This script is never meant to be executed manually on the host.
It's designed exclusively for:
1. Direct execution by notamockd (internal container management)
2. As a Docker ENTRYPOINT (when notamockd generates containers for docker run)

Some parameters can be passed via 'docker run' in Docker mode.
=======================================================================

Usage:
    $0 <variables> <parameters>"
echo "Parameters:
    -c | --config        -  specify config file, default is /etc/notamock.cfg
    -h | --help          -  this help
    -t | --token         -  abf token
    -b | --builder_name  -  common prefix for builder IDs (also known as hostname in abf terminology)
    -p | --parallel      -  number of builders
    --watch              -  Monitor processes using the watch command
                            (optional: specify the line count per process, default $WATCH_LINES)
    --tmux               -  use tmux (with --watch only)
"
exit
}

NOTAMOCKLIB="/usr/share/notamock/libnotamock"
[ -f './libnotamock' ] && NOTAMOCKLIB=./libnotamock
source "$NOTAMOCKLIB"

echo "==> $(basename $0): find parameters"
sep=''
while [ -n "$1" ] ; do
    case "${1}" in
    "-h" | "--help") HLP ;;
    "-c" | "--config")  shift
                        CFG="$1"
                        CFGD='' ;;
    "-t" | "--token") shift ; TOKEN="$1" ;;
    "-b" | "--builder_name") shift ; BUILDER_NAME="$1" ;;
    "-p" | "--parallel") shift ; PARALLEL="$1" ;;
    "-r" | "--release") shift ; PLATFORM="$1" ;;
    "--tmux")   TMUX="yes" ;;
    "--watch" ) WATCH="yes"
                if expr $2 + 1 ; then
                    shift
                    WATCH_LINES="$1"
                fi >/dev/null 2>&1 ;;
    *)  if echo "$1" |grep -q '=' ; then
            VARIABLES="${VARIABLES}${sep}$(echo $1 |sed 's/ /#/g')"
            sep=' '
        else
            echo_exit "Unknown parameter: $1" ${LINENO}
        fi;;
    esac
shift
done
echo "==> $(basename $0): seting up variables from cmdline"

source "$CFG"
VER=${CFG_VERSION:-0.1}
if [ $(echo -e "$VER\n$MIN_VERSION" |sort -V| tail -n1) != "$VER" ] ; then
    echo "Version of config file is less then minimum required for $0.
$VER < $MIN_VERSION
Please update $CFG from /usr/share/notamock/default.notamock.cfg"
    exit
fi

if [ -d "$CFGD" ] ; then
    for a in $(ls -1 ${CFGD}/. |sort ) ; do
        source ${CFGD}/$a
    done
fi

for a in $VARIABLES; do
    echo "==> $(basename $0):  variable: $a"
    a=$(echo $a |sed 's/#/ /g')
    if echo "$a" |grep -q '[[:alnum:]]*+=.*$' ; then
        eval $(echo $a |sed -e 's/=/=("/' -e 's/$/")/')
    elif echo "$a" |grep -q '[[:alnum:]]*=.*$' ; then
        eval $(echo $a |sed -e 's/=/="/' -e 's/$/"/')
    fi
done

PM_opts="$PM_opts \
$PM_cfg_opt $PM_config \
$PM_addrep_opt $PM_cache"

for str in $(seq 0 $(( ${#ENV[@]} - 1 )) ) ; do
    echo "==> $(basename $0): set env: ${ENV[$str]}"
    eval export ${ENV[$str]}
done

echo "==> $(basename $0): Prepare builder environment"
rm -f /etc/localtime
ln -s /usr/share/zoneinfo/UTC /etc/localtime
groupadd mock
useradd -m -G mock,wheel -r omv
[ -d /etc/mock ] && chown -R omv:mock /etc/mock
sed -i -e "s/Defaults    requiretty.*/ #Defaults    requiretty/g" /etc/sudoers
echo "%mock ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers


echo "==> $(basename $0): Installing builder-c and other necessary packages"
vrun $PM_update $PM_opts
vrun $PM_install $PM_opts $BUILDER_list

echo "==> $(basename $0): Fix builder-c scripts path"
sed -i 's:git.*:path = "'"${BUILDER_scripts}"'":' /etc/builder-c/builder.conf
sed -i '/branch/d' /etc/builder-c/builder.conf

echo "==> $(basename $0): Fix sudo suid bit that have been lost in the docker image"
chmod 4111 /usr/bin/sudo

[ -f /ENV.lst ] && vrun source /ENV.lst
vrun export BUILD_TOKEN="${BUILD_TOKEN:-$TOKEN}"
[ $(echo "$BUILD_TOKEN" |wc -c) -lt 10 ] && echo_exit "Need abf token" ${LINENO}
vrun export BUILD_ARCH=$(uname -m)
vrun export BUILD_PLATFORM_TYPE="dnf"
vrun export LOG_LEVEL="${LOG_LEVEL:-"INFO"}"
vrun export BUILD_PLATFORM="${BUILD_PLATFORM:-$BUILDER_platforms}"

if rpm -qa |grep -q angie ; then
    echo "==> $(basename $0): setup сaching proxy"
    CACHE_DIR=${CACHE_DIR:-/tmp/cache}
    CACHE_SIZE=${CACHE_SIZE:-10}
    cat << EOF >> /etc/angie/cproxy.conf
worker_processes auto;
error_log  /var/log/angie/error.log  warn;
events {
    worker_connections 1024;
}

http {
    proxy_cache_path ${CACHE_DIR} levels=1:2 keys_zone=rpm_cache:100m inactive=10d max_size=${CACHE_SIZE}g use_temp_path=off;
    include resolver.conf ;
    server {
        listen 3128;

        location / {
            proxy_pass http://\$http_host;
            proxy_cache rpm_cache;
            proxy_cache_valid 200 302 10d;
            proxy_cache_lock on;
            proxy_set_header Host \$host;
        }

#       location ~* /repodata/ {
#           proxy_pass http://\$http_host;
#           proxy_cache off;
#           add_header X-Cache-Status "DISABLED";
#}
        location ~* /repodata/ {
            proxy_pass http://\$http_host;
            proxy_cache rpm_cache;
            proxy_cache_valid 200 302 10m;
            proxy_cache_lock on;
            proxy_set_header Host \$host;
            add_header X-Cache-Status "SHORT-CACHE-10m";
        }

    }
}
EOF
    mkdir -p "$CHACHE_DIR"
    ln -sf ./cproxy.conf /etc/angie/angie.conf
    echo resolver $(awk 'BEGIN{ORS=" "} $1=="nameserver" {print $2}' /etc/resolv.conf)';' > /etc/angie/resolver.conf
    systemctl start angie.service ||  {
    echo ==> "$(basename $0): systemctl failed, starting Angie manually"
    /usr/sbin/angie -c /etc/angie/angie.conf & }
    export http_proxy='http://127.0.0.1:3128'
else
    echo "==> $(basename $0): make dirs for dnf caches"
    for val in ${BUILD_PLATFORM//,/ }; do
        for a in $(seq -s ' ' $PARALLEL) ; do
            mkdir -p ${DNFCACHE}_${val}_${BUILDER_NAME}_${a}
        done
    done
fi
if [ "$PARALLEL" -ne 1 ] ; then
    for a in $(seq -s ' ' $PARALLEL) ; do
        (vrun export BUILDER_ID=${BUILDER_NAME}_$a
         vrun export BUILD_WORKDIR="/home/omv/$BUILDER_ID"
        mkdir -p "$BUILD_WORKDIR"
        chown omv:omv -R "$BUILD_WORKDIR"
        if [ "$WATCH" ] ; then
            builder > /tmp/${BUILDER_ID} 2>&1
        else
            builder 2>&1
        fi ) &
        echo "==> $(basename r$0): Builder ${BUILDER_NAME}_$a - started"
        sleep 1
    done

    if [ "$WATCH" ] ; then
        wait_cmdline="$(for a in $(seq $PARALLEL) ; do
        echo "echo ${BUILDER_NAME}_$a:"
        echo "find /home/omv/${BUILDER_NAME}_$a/ -maxdepth  2 -name '*.spec'"
        echo "tail -n${WATCH_LINES} /tmp/${BUILDER_NAME}_$a 2>&1"
        echo 'echo'
        done)"
        if [ "$TMUX" ] ; then
            tmux new-session -d -s "notamocka" -n "watch"
            tmux send-keys "watch -t -n 1 \"$wait_cmdline\"" C-m
            tmux attach-session -t "notamocka"
        else
            watch -t -n 1 "$wait_cmdline"
        fi
    else
        exec /bin/bash
    fi
else
    vrun export BUILDER_ID="$BUILDER_NAME"
    vrun export BUILD_WORKDIR="/home/omv/${BUILDER_ID}"
    mkdir -p "$BUILD_WORKDIR"
    chown omv:omv $BUILD_WORKDIR
    if [ "$TMUX" ] ; then
        tmux new-session -d -s "notamocka" -n "builder"
        tmux send-keys "builder" C-m
        tmux attach-session -t "notamocka"
    else
        builder
    fi
fi
