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

pkgnames=(templatectl)
pkgdesc="Tool to add/remove templates for xochitl"
url=https://github.com/PeterGrace/templatectl
pkgver=0.1.3-5
timestamp=2021-01-15T01:23Z
section="templates"
maintainer="Peter Grace <pete.grace@gmail.com>"
license=MIT

image=rust:v2.1
source=("https://github.com/PeterGrace/templatectl/archive/v${pkgver%-*}.zip")
sha256sums=(1ac1049c7db4f87c113dbc96372f8f4e2b8bd4c60252e3c4f7c1fafb5ee61ae4)

build() {
    cargo build --release
}

package() {
    install -D -m 755 -t "$pkgdir"/opt/bin \
        "$srcdir"/target/armv7-unknown-linux-gnueabihf/release/templatectl
    mkdir -p "$pkgdir"/opt/share/toltec/reenable.d
    touch "$pkgdir"/opt/share/toltec/reenable.d/"$pkgname"
}

preinstall() {
    local target_path=share/remarkable/templates
    if [ ! -d /home/root/.entware/"$target_path" ]; then
        mkdir -p /home/root/.entware/"$target_path"
        cp -r /usr/"$target_path"/* /home/root/.entware/"$target_path"
    fi
}

configure() {
    add-bind-mount /home/root/.entware/share/remarkable/templates \
        /usr/share/remarkable/templates

    echo "If you perform a system upgrade that adds new templates"
    echo "Manual intervention may be required to handle adding the new templates"
}

postremove() {
    local bind_path
    local unit_name
    local unit_path
    bind_path=/usr/share/remarkable/templates
    unit_name="$(systemd-escape --path "$bind_path").mount"
    unit_path="/lib/systemd/system/$unit_name"
    if [[ -e $unit_path ]]; then
        remove-bind-mount "$bind_path"
    fi

    echo "To fully remove templatectl you'll need to run the following command:"
    echo "  rm -rf /home/root/.entware/share/remarkable/templates"
}
