#!/bin/bash

set -x -euo pipefail
DAEMON_NAME=pushgateway

log_fatal (){
    logger -ip daemon.error -t ${DAEMON_NAME} "$@"
    exit 1
}

log_info (){
    logger -ip daemon.info -t ${DAEMON_NAME} "$@"
}

# Directory for temporary files
TMPDIR=$(mktemp -d)

install_pushgateway() {
    PUSHGATEWAY_ARCHIVE="https://github.com/prometheus/pushgateway/releases/download/v1.4.2/pushgateway-1.4.2.linux-amd64.tar.gz"
    curl -fS -L --connect-time 3 --max-time 30 --retry 10 "${PUSHGATEWAY_ARCHIVE}" -o ${TMPDIR}/pushgateway.tar.gz || log_fatal "Can't download pushgateway"
    pushd ${TMPDIR}
    tar -zxvf pushgateway.tar.gz || log_fatal "Can't extract pushgateway"
    cp ${TMPDIR}/pushgateway*/pushgateway /usr/local/bin/pushgateway || log_fatal "Can't install pushgateway"
    popd
}

add_user() {
    adduser --system --shell /bin/bash --gecos 'Loadtesting user' --group --disabled-password --home /home/loaduser loaduser
}

cleanup () {
    rm -rf /etc/network/interfaces.d/*
    truncate -s 0 /home/ubuntu/.ssh/authorized_keys || log_fatal "Failed to clean authorized_keys"
    truncate -s 0 /root/.ssh/authorized_keys || log_fatal "Failed to clean root authorized_keys"
    rm -rf /var/log/cloud-init* || log_fatal "Failed to remove cloud-init logs"
    rm -f /etc/hostname
}

main() {
    install_pushgateway
    add_user
    cleanup
}

main
