#!/bin/bash

DTD_FILE="network-settings.dtd"
PROP_FILE="torlauncher.properties"

# remove the trailing colon from the various field labels

strip_colon()
{
  entityName=$1
  sed -i "s/$entityName \"\(.*\)[:：]\"/$entityName \"\1\"/g" $DTD_FILE
}

strip_colon torsettings.useProxy.type
strip_colon torsettings.useProxy.address
strip_colon torsettings.useProxy.port
strip_colon torsettings.useProxy.username
strip_colon torsettings.useProxy.password
strip_colon torsettings.firewall.allowedPorts

# escape special html characters so we can put them in the dtd

escape_string()
{
  string="$1"
  python3 -c "import html; print(html.escape(\"$1\"));"
}

# bring string over from torlauncher.properties and insert into dtd

port_from_properties()
{
  propertyName=$1
  entityName=$2

  string=$(grep $propertyName $PROP_FILE | sed "s/^.*=\(.*\)$/\1/g")
  string=$(escape_string "$string")

  if [ -z "$string" ]; then
    echo "$propertyName not found"
  else
    echo "<!ENTITY $entityName \"$string\">" >> $DTD_FILE
  fi
}

echo "" >> $DTD_FILE
echo "<!-- #31286 about:preferences strings -->" >> $DTD_FILE
port_from_properties torlauncher.request_a_new_bridge torPreferences.requestNewBridge
port_from_properties torlauncher.contacting_bridgedb torPreferences.requestBridgeDialogWaitPrompt
port_from_properties torlauncher.captcha_prompt torPreferences.requestBridgeDialogSolvePrompt
port_from_properties torlauncher.bad_captcha_solution torPreferences.requestBridgeErrorBadSolution
