# Maintainer: Coelacanthus <uwu@coelacanthus.name>

pkgname=uptime-kuma
pkgver=2.4.0
pkgrel=1
pkgdesc="A free and open source uptime monitoring solution"
arch=('x86_64')
url="https://github.com/louislam/uptime-kuma"
license=('MIT')
depends=(
    'nodejs'
    'sqlite'
)
makedepends=(
    'chromium'
    'jq'
    'npm'
    'python'
)
optdepends=(
    'cloudflared: reverse proxy with Cloudflare tunnel'
)
source=(
    "${pkgname}-${pkgver}.tar.gz::${url}/archive/refs/tags/${pkgver}.tar.gz"
    "uptime-kuma.service"
)
b2sums=('3acaafbdf319706718b9dc26207768a6c4c105bd95f6c5a72b000bf90e274cbf27990143d90c7d4509ac9e9ff592b7f6f3061cf283e604a3f855b1906a3a3f19'
        '4a0d02dc226a6d80400d16300f672e7fcf50bdb112e2629e1f1c8177cac499e2ca23f0e3fee4c314f50610b2daea3a98a839c04cd960aaba94765399ffd1b30a')

build() {
    cd ${srcdir}/${pkgname}-${pkgver}
    export PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
    npm ci
    ./node_modules/.bin/vite build --config ./config/vite.config.js
}

package() {
    npm install \
        --build-from-source --sqlite=/usr \
        -g --prefix "${pkgdir}/usr" --cache "${srcdir}/npm-cache" \
        "${srcdir}/${pkgname}-${pkgver}.tar.gz"
    
    install -d ${pkgdir}/usr/lib/node_modules/uptime-kuma/dist/
    cp -r ${srcdir}/${pkgname}-${pkgver}/dist/* -t ${pkgdir}/usr/lib/node_modules/uptime-kuma/dist/

    # npm gives ownership of ALL FILES to build user
    # https://bugs.archlinux.org/task/63396
    chown -R root:root "${pkgdir}"
    
    # Remove references to $pkgdir
    find "$pkgdir" -type f -name package.json -print0 | xargs -0 sed -i "/_where/d"

    # Remove references to $srcdir
    local tmppackage="$(mktemp)"
    local pkgjson="$pkgdir/usr/lib/node_modules/$pkgname/package.json"
    jq '.|=with_entries(select(.key|test("_.+")|not))' "$pkgjson" > "$tmppackage"
    mv "$tmppackage" "$pkgjson"
    chmod 644 "$pkgjson"

    find "$pkgdir" -type f -name package.json | while read pkgjson; do
            local tmppackage="$(mktemp)"
            jq 'del(.man)' "$pkgjson" > "$tmppackage"
            mv "$tmppackage" "$pkgjson"
            chmod 644 "$pkgjson"
    done
    
    install -d ${pkgdir}/usr/lib/systemd/system
    install -Dm644 "${srcdir}/uptime-kuma.service" ${pkgdir}/usr/lib/systemd/system/uptime-kuma.service
    install -Dm644 "${srcdir}/${pkgname}-${pkgver}/LICENSE" ${pkgdir}/usr/share/licenses/${pkgname}/LICENSE
}
