#!/usr/bin/env zsh

s () {
    eval /Software/Sofin/bin/s ${@}
}

which psql >/dev/null
if [ "0" != "${?}" ]; then
    s i Postgresql13
fi
which cargo >/dev/null
if [ "0" != "${?}" ]; then
    s i Rust
fi
which diesel >/dev/null
if [ "0" != "${?}" ]; then
    cargo install diesel_cli --no-default-features --features "postgres"
    s export diesel Rust
fi
which patchelf >/dev/null
if [ "0" != "${?}" ]; then
    s i Patchelf
fi
which smartctl >/dev/null
if [ "0" != "${?}" ]; then
    s i Smartmontools
fi

s env +Postgresql13 +Patchelf +Rust +Smartmontools +Vim

export LD_LIBRARY_PATH=/Software/Postgresql13/lib:/usr/lib

igni dcollector stop
mv /Shared/Igniters/dcollector.igni /tmp/dcollector.igni

cargo build --release \
    && patchelf --set-rpath /Software/Postgresql13/lib target/release/dcollector \
    && mv .env .env.dev \
    && cp /Services/Dcollector/.env ./ \
    && diesel migration run \
    && mv .env.dev .env \
    && install -v target/release/dcollector /Services/Dcollector/bin/dcollector \
    && printf "Deploy completed\n"

mv /tmp/dcollector.igni /Shared/Igniters/dcollector.igni
igni dcollector start

s env reset
