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

pkgnames=(rmfakecloud-proxy)
pkgdesc="Connect Xochitl to a rmfakecloud server"
_url=https://github.com/ddvk/rmfakecloud-proxy
url="$_url"
_upver=0.0.3
pkgver="$_upver-4"
timestamp=2022-02-26T22:59Z
section="utils"
maintainer="Mattéo Delabre <spam@delab.re>"
license=MIT
installdepends=(procps-ng-pgrep findutils)

image=golang:v2.2
source=(
    "https://github.com/ddvk/rmfakecloud-proxy/archive/v$_upver.zip"
    rmfakecloudctl
    rmfakecloud-proxy.service
)
sha256sums=(
    eaa3fdcce250e23f368a4c9ddcfb99ff178decf31b2a7f84501dfc6fdb2e6d8f
    SKIP
    SKIP
)

build() {
    eval "$(go env)"
    cat > version.go << GO
package main
const Version = "rmfakecloud-proxy ${_upver%-*} ($GOOS-$GOARCH) $GOVERSION\n$_url"
GO

    GOARCH=arm GOARM=7 go build -ldflags="-w -s" -o dist/rmfakecloud-proxy
}

package() {
    install -D -m 755 -t "$pkgdir"/opt/bin "$srcdir"/dist/rmfakecloud-proxy
    install -D -m 755 -t "$pkgdir"/opt/bin "$srcdir"/rmfakecloudctl
    install -D -m 644 -t "$pkgdir"/lib/systemd/system "$srcdir"/rmfakecloud-proxy.service
}

configure() {
    # shellcheck source=rmfakecloudctl
    source /opt/bin/rmfakecloudctl
    systemctl daemon-reload

    # Sync the proxy state to the value of its configuration flag
    if is-enabled; then
        # This branch is reached when upgrading the package
        install-certificates
        systemctl enable --now rmfakecloud-proxy
        install-hosts
    else
        uninstall-certificates
        disable-unit rmfakecloud-proxy.service
        uninstall-hosts
    fi

    rmfakecloudctl status
}

preremove() {
    rmfakecloudctl disable
}

postremove() {
    systemctl daemon-reload
}
