#!/usr/bin/env bash
# Copyright (c) 2020 The Toltec Contributors
# SPDX-License-Identifier: MIT

_pkgname="webinterface-wifi"
pkgnames=("$_pkgname")
pkgdesc="View the web interface if running, over wifi"
url="https://github.com/rM-self-serve/$_pkgname"
pkgver=2.0.0-2
timestamp=2023-11-26T00:02:11Z
section="utils"
maintainer="rM-self-serve <122753594+rM-self-serve@users.noreply.github.com>"
license=MIT
image=rust:v3.1

_pkgalias="webint-wifi"
_configdir="/home/root/.config/$_pkgname"
_etcdir="/opt/etc/$_pkgname"

source=(
    "$url/archive/4513d5cbc5e323f2959987f3bc9e300b0aaddb19.zip"
    "$_pkgname-toltec.service"
)

sha256sums=(
    a23c05faf4ccaafea9222255399c8c3a121079dd07970c8768b4315606eb7834
    SKIP
)

build() {
    WIW_DATADIR="/opt/etc" cargo build --release
}

package() {
    install -D -m 755 -t "$pkgdir/opt/bin" \
        "$srcdir/target/armv7-unknown-linux-gnueabihf/release/$_pkgname"
    ln -s "/opt/bin/$_pkgname" "$pkgdir/opt/bin/$_pkgalias"

    install -D -m 644 "$srcdir/$_pkgname-toltec.service" \
        "$pkgdir/lib/systemd/system/$_pkgname.service"

    install -D -m 644 -t "$pkgdir""$_etcdir/docs" \
        "$srcdir/README.MD" "$srcdir"/config/*.toml
    install -D -m 644 -t "$pkgdir""$_etcdir/docs/config_examples" \
        "$srcdir"/config/examples/*.toml
    install -D -m 644 -t "$pkgdir""$_etcdir"/assets \
        "$srcdir/assets/favicon.ico"
    install -d "$pkgdir""$_etcdir/ssl" \
        "$pkgdir""$_etcdir/auth" \
        "$pkgdir""$_configdir"
}

configure() {
    [[ -f "$_configdir/config.toml" ]] \
        || cp "$_etcdir/docs/config.default.toml" \
            "$_configdir/config.toml"

    systemctl daemon-reload

    if is-active "$pkgname"; then
        echo "Restarting $pkgname"
        systemctl restart "$pkgname"
    fi

    echo ""
    echo "Run '\$ $pkgname' for usage information and a link to"
    echo "the documentation. You can also find the documentation locally"
    echo "at /opt/etc/webinterface-wifi/docs/"
    echo ""
    echo "Run the following command to use $pkgname"
    how-to-enable "$pkgname.service"
}

preremove() {
    disable-unit "$pkgname.service"
}

postremove() {
    rmdir "$_etcdir"/*/* "$_etcdir"/* "$_etcdir" 2> /dev/null || true
    systemctl daemon-reload
}
