#!/bin/sh
# Enable installation of unsigned privileged apps on a rooted Firefox OS device.
# Usage: ./setup-device.sh [--undo]
set -e

PROFILE=$(adb shell 'ls -d /data/b2g/mozilla/*.default' | tr -d '\r')
[ -n "$PROFILE" ] || { echo "Firefox OS profile not found" >&2; exit 1; }
echo "Profile: $PROFILE"

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

# b2g rewrites prefs.js on exit, so stop it before editing.
adb shell stop b2g
adb pull "$PROFILE/prefs.js" "$TMP/prefs.js" >/dev/null
cp "$TMP/prefs.js" "./prefs.js.backup-$(date +%Y%m%d-%H%M%S)"
grep -v 'dom.apps.developer_mode' "$TMP/prefs.js" > "$TMP/prefs.new" || true
if [ "$1" != "--undo" ]; then
  echo 'user_pref("dom.apps.developer_mode", true);' >> "$TMP/prefs.new"
fi
adb push "$TMP/prefs.new" "$PROFILE/prefs.js" >/dev/null
adb shell "chmod 600 $PROFILE/prefs.js"
adb shell "grep developer_mode $PROFILE/prefs.js || echo 'developer_mode: off'"
adb shell start b2g
echo "Done, b2g restarted."
