#!/bin/sh
# Shared public identity; private product state remains isolated by numeric UID.
set -eu

ROOT=
if [ "$#" -gt 0 ]; then
    [ "$#" -eq 2 ] && [ "$1" = "--root" ] && [ -d "$2" ] || exit 2
    ROOT=$(cd "$2" && pwd -P)
    [ "$ROOT" != / ] || ROOT=
fi
[ "$(id -u)" -eq 0 ] || { echo "Telemetry setup requires root" >&2; exit 1; }

fail() { echo "R7 telemetry: $*" >&2; exit 1; }
directory() {
    target=$1
    mode=$2
    [ ! -L "$target" ] || fail "Symlink is not allowed: $target"
    if [ ! -e "$target" ]; then
        install -d -o root -g root -m "$mode" "$target"
    fi
    [ -d "$target" ] && [ "$(stat -c %u "$target")" = 0 ] || fail "Expected root-owned directory: $target"
    chmod "$mode" "$target"
}

# Do not follow administrator/user-supplied symlinks as root.
for base in /etc /var /var/lib; do
    [ -d "$ROOT$base" ] && [ ! -L "$ROOT$base" ] || fail "Invalid system directory: $base"
done
directory "$ROOT/etc/r7-license-telemetry" 0755
directory "$ROOT/var/lib/r7-telemetry" 0755
directory "$ROOT/var/lib/r7-telemetry/organizer-pro" 0755
STATE="$ROOT/var/lib/r7-telemetry/organizer-pro/telemetry"
directory "$STATE" 0755
# Sticky bit protects existing user entries; only their owners can read keys.
directory "$STATE/users" 1733

machine=
for source in "$ROOT/etc/machine-id" "$ROOT/var/lib/dbus/machine-id"; do
    if [ -r "$source" ]; then
        machine=$(tr -d '[:space:]' < "$source" | tr 'A-F' 'a-f')
        case "$machine" in *[!0-9a-f]*) machine= ;; esac
        [ "${#machine}" -eq 32 ] && break
        machine=
    fi
done
[ -n "$machine" ] && [ "$machine" != 00000000000000000000000000000000 ] || fail "Initialize the OS machine-id before installing telemetry"

# UUIDv5(NAMESPACE_URL, "r7-workstation:" + lower(machine-id)), unchanged from the client.
digest=$({ printf '\153\247\270\021\235\255\021\321\200\264\000\300\117\324\060\310'; printf 'r7-workstation:%s' "$machine"; } | sha1sum)
digest=${digest%% *}
variant=$(( (0x$(printf '%s' "$digest" | cut -c17) & 3) | 8 ))
device=$(printf '%s-%s-5%s-%x%s-%s' \
    "$(printf '%s' "$digest" | cut -c1-8)" "$(printf '%s' "$digest" | cut -c9-12)" \
    "$(printf '%s' "$digest" | cut -c14-16)" "$variant" "$(printf '%s' "$digest" | cut -c18-20)" \
    "$(printf '%s' "$digest" | cut -c21-32)")
IDENTITY="$ROOT/var/lib/r7-telemetry/device-id"
[ ! -L "$IDENTITY" ] || fail "Symlink is not allowed: $IDENTITY"
if [ ! -e "$IDENTITY" ]; then
    temp=$(mktemp "$ROOT/var/lib/r7-telemetry/.device-id.XXXXXX")
    trap 'rm -f "$temp"' EXIT HUP INT TERM
    printf '%s\n' "$device" > "$temp"
    chmod 0644 "$temp"
    # Link is atomic and does not overwrite another product's identity.
    ln "$temp" "$IDENTITY" 2>/dev/null || test -f "$IDENTITY"
    rm -f "$temp"
    trap - EXIT HUP INT TERM
fi
[ -f "$IDENTITY" ] && [ "$(stat -c %u "$IDENTITY")" = 0 ] || fail "Invalid common device-id owner"
[ "$(cat "$IDENTITY")" = "$device" ] || fail "Common device-id does not match this machine; no identity was changed"
chmod 0644 "$IDENTITY"

# Move the entire legacy directory, including keys, lock inode and sequence counters.
# Open directory/lock descriptors of a running client continue to address the same inodes.
LEGACY="$ROOT/var/lib/r7/organizer-pro/telemetry"
if [ -e "$LEGACY/state.json" ]; then
    for base in "$ROOT/var/lib/r7" "$ROOT/var/lib/r7/organizer-pro"; do
        [ ! -L "$base" ] && [ "$(stat -c %u "$base")" = 0 ] || fail "Invalid legacy parent: $base"
    done
    [ -d "$LEGACY" ] && [ ! -L "$LEGACY" ] && [ ! -L "$LEGACY/state.json" ] || fail "Invalid legacy state"
    owner=$(stat -c %u "$LEGACY")
    destination="$STATE/users/$owner"
    [ ! -e "$destination" ] && [ ! -L "$destination" ] || fail "Both legacy and per-user state exist; administrator migration is required"
    chmod 0700 "$LEGACY"
    mv -T -n "$LEGACY" "$destination"
    [ ! -e "$LEGACY" ] || fail "Migration target appeared concurrently; legacy state was preserved"
fi

echo "R7 telemetry directories and common device-id are ready"
