#!/bin/sh
set -eu
umask 077
TARGET=${SYNOPKG_PKGDEST:-/var/packages/ddnsto/target}
DATA=${SYNOPKG_PKGVAR:-/var/packages/ddnsto/etc}
mkdir -p "$DATA" "$TARGET/bin"
chmod 700 "$DATA"
# Keep permanent state first, then migrate an in-place or legacy installation.
for name in ddnsto-config.json .ddnsto_boot.cfg; do
    if [ ! -f "$DATA/$name" ]; then
        if [ -f "$TARGET/bin/$name" ]; then
            cp "$TARGET/bin/$name" "$DATA/$name"
        elif [ "$name" = ddnsto-config.json ] && [ -f /tmp/.ddnsto/ddnsto-config.json ]; then
            cp /tmp/.ddnsto/ddnsto-config.json "$DATA/$name"
        fi
    fi
done
if [ ! -f "$DATA/ddnsto-config.json" ]; then
    TOKEN=${wizard_ddnsto_token:-}
    INDEX=${wizard_ddnsto_idx:-0}
    case "$TOKEN" in
        ''|*[!a-zA-Z0-9_-]*) echo "Invalid or missing DDNSTO Token" >&2; exit 1 ;;
    esac
    case "$INDEX" in
        ''|*[!0-9]*) echo "Device index must be an integer from 0 to 99" >&2; exit 1 ;;
    esac
    INDEX=$(printf '%s' "$INDEX" | sed 's/^0*//')
    INDEX=${INDEX:-0}
    if [ "${#INDEX}" -gt 2 ]; then
        echo "Device index must be from 0 to 99" >&2
        exit 1
    fi
    printf '{"token":"%s","routeridx":%s}\n' "$TOKEN" "$INDEX" > "$DATA/ddnsto-config.json"
fi
if [ ! -f "$DATA/.ddnsto_boot.cfg" ]; then
    printf '0\n' > "$DATA/.ddnsto_boot.cfg"
fi
for name in ddnsto-config.json .ddnsto_boot.cfg; do
    chmod 600 "$DATA/$name"
    ln -sfn "$DATA/$name" "$TARGET/bin/$name"
done
# dsmuidir in INFO lets DSM register the desktop entry.
