#!/bin/bash

set -e

ELMDISTURL=https://github.com/elm/compiler/releases/download/0.19.0/binaries-for-linux.tar.gz
SRCDIR=/usr/share/gocode/src/github.com/prometheus/alertmanager/ui/app
DSTDIR=/usr/share/prometheus/alertmanager/ui

echo "Installing dependencies..." >&2
apt install libjs-bootstrap4 fonts-font-awesome curl uglifyjs \
    golang-github-prometheus-alertmanager-dev

#/usr/share/fonts-font-awesome/
TMPDIR=$(mktemp -d)

echo "Downloading Elm tools..." >&2
curl --location $ELMDISTURL | tar xz -C $TMPDIR

echo "Compiling source code..." >&2
ln -s $SRCDIR/src $SRCDIR/elm.json $TMPDIR
(cd $TMPDIR; ./elm make src/Main.elm --optimize --output $TMPDIR/app.js)

echo "Optimising source code..." >&2
uglifyjs $TMPDIR/app.js \
    --compress 'pure_funcs="F2,F3,F4,F5,F6,F7,F8,F9,A2,A3,A4,A5,A6,A7,A8,A9",pure_getters,keep_fargs=false,unsafe_comps,unsafe' \
    --mangle --output $TMPDIR/script.js

echo "Installing in Alertmanager directory..." >&2
mkdir -p $DSTDIR
mkdir -p $DSTDIR/lib
cp $TMPDIR/script.js $DSTDIR
cp $SRCDIR/index.html $SRCDIR/favicon.ico $DSTDIR
ln -s /usr/share/fonts-font-awesome $DSTDIR/lib/font-awesome
ln -s /usr/share/nodejs/bootstrap/dist $DSTDIR/lib/bootstrap4

rm -rf $TMPDIR

echo "Finished! Please, restart prometheus-alertmanager to activate UI." >&2
