#!/usr/bin/env bash
set -euo pipefail

declare -a flags=([0]=patch_rm2fb)
declare -- timestamp=2021-05-02T14:39Z
declare -a source=([0]=https://github.com/LinusCDE/plato/archive/0.9.17-rm-release-10.zip)
declare -a sha256sums=([0]=25aae17979d9e259d228617eb26a0cc89a6251968b8fc355b8cde36fd6b26773)
declare -a noextract=()
declare -a makedepends=([0]=build:jq [1]=build:unzip [2]=build:wget)
declare -- maintainer='Linus K. <linus@cosmos-ink.net>'
declare -- image=rust:v1.6
declare -- arch=rmall
declare -a pkgnames=([0]=plato)
declare -- pkgname=plato
declare -- pkgver=0.9.17-1
declare -- pkgdesc='Document reader'
declare -- url=https://github.com/LinusCDE/plato
declare -- section=readers
declare -- license=AGPL-3.0-or-later
declare -a installdepends=([0]=display [1]=jq)
declare -a conflicts=()
declare -a replaces=()




is-enabled() {
    systemctl --quiet is-enabled "$1" 2> /dev/null
}

is-active() {
    systemctl --quiet is-active "$1" 2> /dev/null
}

get-conflicts() {
    systemctl show "$1" | awk -F'=' '/^Conflicts=/{print $2}' \
        | sed 's|\bshutdown.target\b||'
}

how-to-enable() {
    for conflict in $(get-conflicts "$1"); do
        if is-enabled "$conflict"; then
            echo "$ systemctl disable --now ${conflict/.service/}"
        fi
    done

    echo "$ systemctl enable --now ${1/.service/}"
}

reload-oxide-apps() {
    if ! is-active tarnish.service; then
        return
    fi
    echo -n "Reloading Oxide applications: "
    if ! /opt/bin/rot apps call reload 2> /dev/null; then
        echo "Failed!"
    else
        echo "Done!"
    fi
}

add-bind-mount() {
    local unit_name
    local unit_path
    unit_name="$(systemd-escape --path "$2").mount"
    unit_path="/lib/systemd/system/$unit_name"

    if [[ -e $unit_path ]]; then
        echo "Bind mount configuration for '$2' already exists, updating"
    else
        echo "Mounting '$1' over '$2'"
    fi

    cat > "$unit_path" << UNIT
[Unit]
Description=Bind mount $1 over $2
DefaultDependencies=no
Conflicts=umount.target
Before=local-fs.target umount.target

[Mount]
What=$1
Where=$2
Type=none
Options=bind

[Install]
WantedBy=local-fs.target
UNIT

    systemctl daemon-reload
    systemctl enable "$unit_name"
    systemctl restart "$unit_name"
}

remove-bind-mount() {
    local unit_name
    local unit_path
    unit_name="$(systemd-escape --path "$1").mount"
    unit_path="/lib/systemd/system/$unit_name"

    if [[ ! -e $unit_path ]]; then
        echo "No existing bind mount for '$1'"
        return 1
    fi

    echo "Removing mount over '$1'"
    systemctl disable "$unit_name"
    systemctl stop "$unit_name"
    rm "$unit_path"
    systemctl daemon-reload
}

if [[ $1 = configure ]]; then
    script() {

 
    local mediadir=/home/root/plato-media;
    if [ ! -d $mediadir ]; then
        mkdir $mediadir;
        echo "";
        echo "Place your media files for plato in '$mediadir'";
        echo "";
    else
        local metadata_file=$mediadir/.metadata.json;
        local metadata_file_old=$mediadir/.metadata-old.json;
        local max_key_len;
        [ -e $metadata_file ] && max_key_len=$(jq --raw-output 'keys[]' < $metadata_file | wc -L) || max_key_len=-1;
        if [ "$max_key_len" -gt 16 ] && [ ! -e $metadata_file_old ]; then
            echo "";
            echo "In Plato 0.9.14 the metadata format for libraries changed.";
            echo "Found your outdated metadata file. Will update it automatically...";
            mv $metadata_file $metadata_file_old;
            local change_cmds="";
            local del_list="";
            for key in $(jq --raw-output 'keys[]' < $metadata_file_old);
            do
                hex_key=$(printf %016X "$key");
                [ -z "$del_list" ] || del_list="${del_list}, ";
                [ -z "$change_cmds" ] || change_cmds="${change_cmds} | ";
                del_list="${del_list}.[\"${key}\"]";
                change_cmds="${change_cmds}.[\"$hex_key\"] = .[\"$key\"]";
            done;
            jq "$change_cmds | del($del_list)" < $metadata_file_old > $metadata_file;
            echo "Update complete. The old file was renamed to '.metadata-old.json'.";
            echo "";
        else
            if [ "$max_key_len" -gt 16 ] && [ -e $metadata_file_old ] || [ ! -e $metadata_file ]; then
                echo "";
                echo "In Plato 0.9.14 the metadata format for libraries changed.";
                echo "MANUAL INTERVENTION REQUIRED\!\!\!";
                echo "Please follow the following guide to update your library metadata manually:";
                echo "https://github.com/baskerville/plato/releases/tag/0.9.14";
                echo "Please LAUNCH plato ONLY AFTER this was done\!";
                echo "";
            fi;
        fi;
    fi

    }
    script
fi
