#!/bin/bash
#
#    Copyright (C) 2008-2023  Ruben Rodriguez <ruben@trisquel.info>
#    Copyright (C) 2015       Santiago Rodriguez <santi@trisquel.info>
#    Copyright (C) 2025       Luis Guzman <ark@switnet.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

VERSION=120
EXTERNAL='deb-src http://ppa.launchpadcontent.net/mozillateam/ppa/ubuntu $UPSTREAM main'
REPOKEY=9BDB3D89CE49EC21

. ./config

# SHA256 HASHES UPDATES
GLEAN_CONF_RS_INITIAL=$(sha256sum third_party/rust/glean/src/configuration.rs|awk '{print$1}')
# GNUZILLA ADDON REPLACEMENT
OLD_WEB_DEV_URL="https://addons.mozilla.org/firefox/collections/mozilla/webdeveloper/"
WEB_DEV_URL="https://gnuzilla.gnu.org/mozzarella/category.php?id=web-development"

rm debian/control
sed "s|Safe and easy web browser from Mozilla|Safe and easy web browser from Mozilla by Trisquel|" \
  -i debian/control.in

# Disable remote settings antifeature.
sed '/async download.*/a\ \ \ \ return null;' -i services/settings/Attachments.sys.mjs
sed "/async download.*/a\ \ \ \ console.warn(\"Function 'fetchLatestChanges' disabled in Abrowser due privacy concerns.\");" \
  -i services/settings/Attachments.sys.mjs
# More info at $DATA/patch_changes/007_disable_remote_settings_antifeature.patch

# Disable activity-stream antifeatures.
# These are not condensed into a single sed script to make it fail on individual commands that didn't change the source
ActivityStream=browser/components/newtab/lib/ActivityStream.sys.mjs
BAP_FirefoxJs=browser/app/profile/firefox.js
sed '/^const DEFAULT_SITES/,/^])\;/c const DEFAULT_SITES = new Map\([[""]]\);' -i browser/components/newtab/lib/DefaultSites.sys.mjs
sed '/"showSponsored"/,/value/s/value: true/value: false/' -i $ActivityStream
sed '/"telemetry"/,/value/s/value: true/value: false/' -i $ActivityStream
sed '/"section.highlights.includePocket"/,/value/s/value: true/value: false/' -i $ActivityStream
sed '/"telemetry.structuredIngestion.endpoint"/,/value/s/value: .*/value: ""/' -i $ActivityStream
sed '/read_more_endpoint/,+1s/http.*/",/' -i $ActivityStream
sed '/stories_endpoint/s/getpocket.cdn.mozilla.net/127.0.0.1/' -i $ActivityStream
sed '/stories_referrer/s/http.*/",/' -i $ActivityStream
sed '/topics_endpoint/s/getpocket.cdn.mozilla.net/127.0.0.1/' -i $ActivityStream
sed 's/preffedRegions.includes.geo. .. ..locales .. locales.includes.locale./false/' -i $ActivityStream
#sed 's/Ubuntu, //' -i browser/components/newtab/css/activity-stream*.css
#echo "#header-asrouter-container{display: none!important;}" >> browser/components/newtab/css/activity-stream-linux.css
#Disable «Sponsored tiles on the New Tab page» - firefox 92+94
sed '/"showSponsoredTopSites"/,/value/s/value: true/value: false/' -i $ActivityStream
sed -i '/activity-stream.showSponsored/s|true|false|g' $BAP_FirefoxJs
#Disable «Mozilla VPN» - firefox 94
sed '/"browser.privatebrowsing.vpnpromourl"/s/https.*"/"/' -i $BAP_FirefoxJs
grep -rl browser.vpn_promo.enabled | xargs -r sed -i '/browser.vpn_promo.enabled/s|true|false|'

sed '/network.connectivity-service.IPv/s/http.*success.txt?ipv[46]//' -i modules/libpref/init/all.js
sed 's/accounts-static.cdn.mozilla.net.*sync.services.mozilla.com//' -i modules/libpref/init/all.js

# Disable 106 firefox-view and other firefox-branded popups
/bin/sed -i '/browser.urlbar.quicksuggest.shouldShowOnboardingDialog/s|true|false|' $BAP_FirefoxJs
sed -i '/services.sync.prefs.sync.browser.firefox-view.feature-tour/s|true|false|' $BAP_FirefoxJs
##disable firefox-view
##sed -i '/"browser.tabs.firefox-view"/s|true|false|' browser/app/profile/firefox.js #deprecated -v127
##disable ui tour
sed -i '/browser.uitour.enabled/s|true|false|' $BAP_FirefoxJs
##disable colorways closet
sed -i '/browser.theme.colorway-closet/s|true|false|' $BAP_FirefoxJs
##disable newtab intro - check adjustment for versions greater than 106
#grep -rl browser.newtabpage.introShown |xargs -r sed -i '/browser.newtabpage.introShown/s|true|false|'
##Remove mailto handlers. 110
##More info at $DATA/patch_changes/006_remova_mailto_handlers_correctly.patch
# keep contentRelevancy disabled (first appearence is false thus using /bin/sed)
/bin/sed -i '/"toolkit.contentRelevancy.ingestEnabled"/s|,.*)|, false)|' $BAP_FirefoxJs

# Replace ubufox recommendation
sed 's/xul-ext-ubufox/webext-ublock-origin/' -i debian/control.in

#Remove exceptions on warnings when installing addons.
sed -i '/addons.mozilla.org/d' browser/app/permissions

# Disable healtreport
cat << EOF > toolkit/components/telemetry/healthreport-prefs.js
pref("datareporting.healthreport.uploadEnabled", false);
pref("datareporting.healthreport.about.reportUrl", "https://trisquel.info/legal");
pref("datareporting.healthreport.infoURL", "https://trisquel.info/legal");
EOF
# Replace privacy page
grep -rl https://www.mozilla.org/legal/privacy/ | \
    xargs -r sed -i 's|https://www.mozilla.org/legal/privacy/.*"|https://trisquel.info/legal"|'

# Disable telemetry pings
grep -rl TELEMETRY_BASE_URL | xargs -r sed -i 's|"https://incoming.telemetry.mozilla.org/submit"|""|'
grep -rl '"https://incoming.telemetry.mozilla.org"'| xargs -r sed -i 's|"https://incoming.telemetry.mozilla.org"|"http://127.0.0.1"|'
grep -rl toolkit.telemetry.server_owner modules/| xargs -r sed -i '/toolkit.telemetry.server_owner/s|Mozilla|None|'
grep -rl toolkit.telemetry.unified | xargs -r sed -i '/toolkit.telemetry.unified/s|[Tt]rue|false|'
grep -rl toolkit.telemetry.archive.enabled | xargs -r sed -i '/toolkit.telemetry.archive.enabled/s|true|false|'
grep -rl toolkit.telemetry.updatePing.enabled | xargs -r sed -i '/toolkit.telemetry.updatePing.enabled/s|true|false|'
grep -rl toolkit.telemetry.shutdownPingSender.enabled  | xargs -r sed -i '/toolkit.telemetry.shutdownPingSender.enabled/s|[Tt]rue|false|'
grep -rl toolkit.telemetry.newProfilePing.enabled | xargs -r sed -i '/toolkit.telemetry.newProfilePing.enabled/s|true|false|'
grep -rl toolkit.telemetry.firstShutdownPing.enabled | xargs -r sed -i '/toolkit.telemetry.firstShutdownPing.enabled/s|true|false|'
grep -rl toolkit.telemetry.bhrPing.enabled  | xargs -r sed -i '/toolkit.telemetry.bhrPing.enabled/s|true|false|'
# fixed by https://bugzilla.mozilla.org/show_bug.cgi?id=1868988
#grep -rl security.certerrors.recordEventTelemetry | xargs -r sed -i '/security.certerrors.recordEventTelemetry/s|true|false|'
grep -rl services.sync.telemetry.maxPayloadCount modules/ | xargs -r sed -i '/services.sync.telemetry.maxPayloadCount/s|500|-1|'
grep -rl services.sync.telemetry.submissionInterval modules/ | xargs -r sed -i '/services.sync.telemetry.submissionInterval/s|43200|-1|'
echo 'pref("dom.security.unexpected_system_load_telemetry_enabled", false);' | tee -a $BAP_FirefoxJs
echo 'pref("toolkit.telemetry.hybridContent.enabled", false);' | tee -a $BAP_FirefoxJs
# GPC opt-out entry added on 120 (not enabled yet).
echo '//pref("privacy.globalprivacycontrol.enabled", true);' | tee -a $BAP_FirefoxJs
# Disable translataion popup
grep -rl browser.translations.automaticallyPopup modules/ | xargs -r sed -i '/browser.translations.automaticallyPopup/s|true|false|'
# Disable Firefox Relay
sed -i '/signon.firefoxRelay.feature/c pref("signon.firefoxRelay.feature", "disabled");' $BAP_FirefoxJs

# Disable autoupdate GMP chromium repo & extensions
sed -i '/media.gmp-manager.chromium-update-url/s|https://update.googleapis.com/service.*"|"|' $BAP_FirefoxJs
sed -i 's|\(pref("media\.gmp-widevinecdm-l1\.chromium-guid", \)"[^"]*"|\1""|' $BAP_FirefoxJs
sed -i 's|\(pref("media\.gmp-widevinecdm\.chromium-guid", \)"[^"]*"|\1""|' $BAP_FirefoxJs

# Update third_party/rust/glean/src/configuration.rs sha256sum at third_party/rust/glean/.cargo-checksum.json
GLEAN_CONF_RS_MODIFIED=$(sha256sum third_party/rust/glean/src/configuration.rs|awk '{print$1}')
sed_csum $GLEAN_CONF_RS_INITIAL \
         $GLEAN_CONF_RS_MODIFIED

# Remove Google API key and calls
sed '/Google API/,/google-api-keyfile/ d' debian/config/mozconfig.in -i
sed '/"geo.provider.network.url"/s|https.*"|"|' -i modules/libpref/init/all.js

# Disable save password in browser suggestion.
#grep -lr '^pref("signon.rememberSignons"'| xargs sed -i "/^pref(\"signon.rememberSignons\"/s|true|false|" modules/libpref/init/all.js

# Org branding
sed 's/com.ubuntu/org.trisquel/' -i debian/config/mozconfig.in

# Disable DRM support, armhf has no such option.
## Add other archs that might present the same lack of disable-eme option
cat << ARCH >> debian/config/mozconfig.in
%%if DEB_HOST_ARCH != ppc64el
%%if DEB_HOST_ARCH != arm64
%%if DEB_HOST_ARCH != armhf
ac_add_options --disable-eme
%%endif
%%endif
%%endif
ARCH

cat << SIGN >> debian/config/mozconfig.in
export MOZ_REQUIRE_SIGNING=
SIGN

sed '/gmp-clearkey/d' -i ./debian/firefox.install.in

# Locale packages should provide firefox-locale-$LANG
sed "s/Provides.*/Provides: abrowser-locale-@LANGCODE@/" -i debian/control.langpacks
sed 's/Firefox/Abrowser/' -i debian/control.langpacks

# Provide firefox
sed "s/iceweasel,/iceweasel, firefox,/" -i debian/control.in

# Remove Ubuntu bookmarks
sed -i /ubuntu-bookmarks/d debian/patches/series
rm debian/patches/ubuntu-bookmarks*

# Custom newtab images at DATA/firefox/search-custom/

cp $DATA/newtab/*.ico browser/components/newtab/data/content/tippytop/favicons/
cp $DATA/newtab/*.png browser/components/newtab/data/content/tippytop/images/

#Trisquel custom search engines
#cp -a $DATA/searchplugins/* browser/components/search/extensions/
/bin/sed "/\"data\": \[/ r $DATA/searchplugins/trisquel-v2.json" -i ./services/settings/dumps/main/search-config-v2.json
/bin/sed "/\"data\": \[/ r $DATA/searchplugins/trisquel-packages-v2.json" -i ./services/settings/dumps/main/search-config-v2.json
# Setup trisquel's searchengine icons
ICONS_FOLDER="services/settings/dumps/main/search-config-icons"
for id in \
    "b99ed276-9557-4492-8bbb-d59826381893" \
    "b5fd21a8-e369-477f-a3f2-b47a370f9030"
do
    ## customize id value
    echo "$id" | grep -q "b99ed276" && json_name="trisquel.json"
    echo "$id" | grep -q "b5fd21a8" && json_name="trisquel-packages.json"
    ## copy icons and json definitons.
    cp "$DATA/trisquel-search-icons/$id.png" "$ICONS_FOLDER/$id"
    cp "$DATA/trisquel-search-icons/${id:0:8}-${json_name}" "$ICONS_FOLDER/$id.meta.json"
done
## Add references to moz.build
python3 $DATA/trisquel-search-icons/update_mozbuild.py

## Set json in search-config-icons.json
jq --slurpfile newIcon1 "$DATA/trisquel-search-icons/b99ed276-trisquel.json" \
   --slurpfile newIcon2 "$DATA/trisquel-search-icons/b5fd21a8-trisquel-packages.json" \
   '.data += [$newIcon1[0], $newIcon2[0]]' services/settings/dumps/main/search-config-icons.json > tmp-s-c-i.json && \
   mv tmp-s-c-i.json services/settings/dumps/main/search-config-icons.json

echo "Customizing search engines..."
# Reprocess search preconfiguration dump
python3 $DATA/process-json-files.py . $DATA/search-custom/

cat << EOF > debian/distribution.ini
[Global]
id=trisquel
version=$REVISION
about=Abrowser for Trisquel GNU/Linux

[Preferences]
app.distributor = "trisquel"
app.distributor.channel = "trisquel"
app.partner.ubuntu = "trisquel"
intl.locale.requested=""
EOF

sed  "s/^MOZ_APP_NAME\t.*/MOZ_APP_NAME\t\t:= abrowser/;" debian/build/config.mk -i
sed  "s/^MOZ_PKG_NAME\t.*/MOZ_PKG_NAME\t\t:= abrowser/;" debian/build/config.mk -i

############################################################################3
############################################################################3
############################################################################3

# Branding files
cp -a $DATA/branding/* browser/branding/official
cp -a $DATA/branding/* browser/branding/unofficial
cp -a $DATA/branding/* browser/branding/nightly
cp -a $DATA/branding/* browser/branding/aurora
# We are using unofficial but also should have abrowser word on the about window.
cp browser/branding/official/content/jar.mn browser/branding/unofficial/content/jar.mn
echo '#warningDesc, #communityExperimentalDesc, #communityDesc, #contributeDesc {display:none!important}' >> browser/base/content/aboutDialog.css

# Replace/remove brand name on used view(s) to avoid branding issues.
for i in $(find . -name brandings.ftl)
do
    /bin/sed -i '/firefoxview-brand-name/s|Firefox View|Abrowser View|' $i
    sed -i 's|= Firefox |= |' $i
done

# Disable preprocessor
sed 's/_PP//' -i browser/branding/branding-common.mozbuild
#Prevent duplicated values.
cat << EOF > debian/config/branch.mk
MOZILLA_REPO = https://hg.mozilla.org/releases/mozilla-release
L10N_REPO = https://hg.mozilla.org/l10n-central
CHANNEL                 = release
MOZ_WANT_UNIT_TESTS     = 0
MOZ_OFFICIAL_BUILD      = 0
MOZ_ENABLE_BREAKPAD     = 0
MOZ_ENABLE_TELEMETRY    = 0
EOF

SEDSCRIPT="
s|Updates from { -vendor-short-name } and { -brand-product-name }|Updates from { -vendor-short-name }|;
s/Try Firefox/Try Abrowser/g;
s/Firefox Home/Abrowser Home/g;
s/Firefox Account/Sync Account/g;
s/Updates from Mozilla and Firefox/Updates from Mozilla/g;
s/Adobe Flash/Flash/g;
s|www.mozilla.com/firefox/central|trisquel.info/browser|g;
s|mozilla.com/plugincheck|trisquel.info/browser|g;
s|www.mozilla.com/legal/privacy|trisquel.info/legal|g;
s|Firefox Nightly|Abrowser|;
s|Firefox Developer Edition|Abrowser|g;
s|Nightly|Abrowser|g;
s|brand-product-name = Firefox|brand-product-name = Abrowser|;
s|Sign in to Firefox|Sign in to Sync|;
s|Search addons.mozilla.org|Search|g;
s|firefox.settings.services.mozilla.com|127.0.0.1|g;
s|this-firefox|this-abrowser|g;
s|firefox-help|abrowser-help|g;
"

echo "Running batch replace operation"
find . -type f -not -iregex '.*changelog.*' -not -iregex '.*copyright.*' -not -iregex '.*third_party/.*' -execdir /bin/sed --follow-symlinks -i "$SEDSCRIPT" '{}' ';'

echo "Replacing Firefox with Abrowser on ./l10n"
find l10n -type f  -not -iregex '.*changelog.*' -not -iregex '.*copyright.*' -execdir /bin/sed --follow-symlinks -i "s/Firefox/Abrowser/" '{}' ';'

sed 's/Firefox/Abrowser/' -i debian/control.in \
                             browser/locales/en-US/chrome/overrides/appstrings.properties

sed s/ubuntu/trisquel/g debian/distribution.ini -i
sed "s/ubuntu_version/trisquel_version/; s/Ubuntu 10.10/Trisquel $REVISION/; s/1010/40/" -i debian/firefox.postinst.in

# Delete stuff we don't use and that may contain trademaked logos
##keeping "windows" icons for ff96
rm -rf ./browser/metro ./addon-sdk/source/doc/static-files/media ./browser/themes/osx ./b2g

#Trisquel custom bookmarks
cp $DATA/default-bookmarks.html browser/base/content/default-bookmarks.html

# install extensions
for extension in $(ls -1 $DATA/extensions/); do
  cp $DATA/extensions/$extension -r debian
  echo "debian/$extension @MOZ_ADDONDIR@/extensions/" >> debian/abrowser.install.in
done

# Disable search field at extensions panel
#sed  '/header-search/d; /search.placeholder/d' -i toolkit/mozapps/extensions/content/extensions.xul
cat << EOF >> toolkit/mozapps/extensions/content/extensions.css
#header-search {
  display:none;
}
EOF

# Hide mobile promo
echo ".fxaMobilePromo {  display: none !important; }" >> browser/themes/shared/preferences/preferences.inc.css
# Hide unwanted elements on about:addons
echo ".discopane-notice, .privacy-policy-link, #main header, #plugindeprecation-notice {  display: none !important; }" >> toolkit/mozapps/extensions/content/aboutaddons.css
# Hide warnings on unsigned extensions
echo ".warning{display: none!important; } .addon[notification=warning]{background-image: none!important;}" >> toolkit/mozapps/extensions/content/extensions.css
# Hide extra links in about box

# about: page mods, like rights.
## Hide extra links in about box
#find -wholename '*/brand.dtd' |xargs /bin/sed 's/trademarkInfo.part1.*/trademarkInfo.part1 "">/' -i

##Remove invalid policy for trisquel.
# see more at DATA/firefox/patch_changes/008_aboutRights_removal_fix.patch

#EO about: mods.

sed -i 's|<a href="http://www.mozilla.org/">Mozilla Project</a>|<a href="http://www.trisquel.info/">Trisquel Project</a>|g' browser/base/content/overrides/app-license.html
sed -i 's|https://firefox-source-docs.mozilla.org/contributing/contribution_quickref.html|https://gitlab.trisquel.org/trisquel/package-helpers|' toolkit/content/license.html

# We went too far...
#sed -i 's/iceweasel, abrowser, icecat,/iceweasel, firefox, icecat,/g' debian/control.in
sed '/Provides/s/abrowser-locale/firefox-locale/' -i debian/control.langpacks
/bin/sed '/trademarkInfo/s/Abrowser/Firefox/' -i l10n/*/browser/branding/official/brand.ftl

# js settings
cat $DATA/settings.js >> debian/vendor-firefox.js

# set contentblocking to strict by default
patch_p1 $DATA/default-strict.patch
#sed '/this._trackSlowStartup/s/$/\n\n if (! Services.prefs.prefHasUserValue("browser.contentblocking.category")) { Services.prefs.setStringPref("browser.contentblocking.category", "strict"); this._updateCBCategory; }/' -i ./browser/components/BrowserGlue.jsm

#################
# Android stuff #
#################

# Settings
cat << EOF >> mobile/android/confvars.sh
# Abrowser settings
MOZ_APP_BASENAME=Abrowser
MOZ_APP_VENDOR=Trisquel
MOZ_PAY=0
MOZ_SERVICES_HEALTHREPORT=0
MOZ_SERVICES_HEALTHREPORTER=0
MOZ_SERVICES_METRICS=0
MOZ_DATA_REPORTING=0
MOZ_DEVICES=0
MOZ_ANDROID_GOOGLE_PLAY_SERVICES=0
MOZ_TELEMETRY_REPORTING=0
MOZ_ADDON_SIGNING=0
EOF

#Enable EGL by default
sed -i '/gfx.x11-egl.force-enabled/,/mirror/s|false|true|' modules/libpref/init/StaticPrefList.yaml

# Branding
rm mobile/android/branding/{official,unofficial,beta,nightly} -rf
cp -a $DATA/android/branding/ mobile/android/branding/official
cp $DATA/android/mobile.ico mobile/android/app/
#cp $DATA/android/images/* mobile/android/themes/core/images/
cp -a $DATA/android/res/main/* mobile/android/geckoview/src/main/res

# Rebrand svg & debug tools & privacy logos
find devtools/client/themes/images/ -name aboutdebugging-firefox-*.svg | xargs -n1 cp $DATA/debug_brand/debuglogo.svg
find devtools/client/themes/images/ -name aboutdebugging-fenix*.svg | xargs -n1 cp $DATA/debug_brand/debuglogo.svg
find devtools/client/themes/images/ -name aboutdebugging-firefox-logo.svg | xargs -n1 cp $DATA/debug_brand/debuglogo_gray.svg

find browser/branding/ -name about-logo.svg | xargs -n1 cp $DATA/debug_brand/debuglogo.svg

find browser/branding/ -name about-logo-private.png | xargs -n1 cp $DATA/debug_brand/about-logo-private.png
find browser/branding/ -name about-logo-private@2x.png | xargs -n1 cp $DATA/debug_brand/about-logo-private@2x.png
find browser/branding/ -name PrivateBrowsing_70.png | xargs -n1 cp $DATA/debug_brand/PrivateBrowsing_70.png
find browser/branding/ -name PrivateBrowsing_150.png | xargs -n1 cp $DATA/debug_brand/PrivateBrowsing_150.png

# Replace addons placeholder for the gnuzilla mozzarella.
find l10n/ -name aboutAddons.ftl | xargs -r sed -i '/.placeholder/s|addons.mozilla.org|gnuzilla.gnu.org|g'
sed -i "s|$OLD_WEB_DEV_URL|$WEB_DEV_URL|" devtools/client/menus.js
grep -lr addons-help toolkit/mozapps/extensions/ | xargs -r sed -i 's|addons-help|abrowser-help|'

#Fixes by patch on source, see DATA/firefox/patches for more info.
for patch in $(ls -v ${DATA}/patch_changes/*.patch)
do
    patch_p1 $patch
done

# Postinst script to manage profile migration and system links
echo '

if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] ; then

[ -f /usr/bin/firefox ] || ln -s /usr/bin/abrowser /usr/bin/firefox

for HOMEDIR in $(grep :/home/ /etc/passwd |grep -v usbmux |grep -v syslog|cut -d : -f 6)
do
    [ -d $HOMEDIR/.mozilla/abrowser ] && continue || true
    [ -d $HOMEDIR/.mozilla/firefox ] || continue
    echo Linking $HOMEDIR/.mozilla/firefox into $HOMEDIR/.mozilla/abrowser
    ln -s $HOMEDIR/.mozilla/firefox $HOMEDIR/.mozilla/abrowser
done
fi
exit 0 ' >> debian/abrowser.postinst.in

sed 's/1410/65/; s/1310/60/' -i debian/rules

sed 's/^Source:.*/Source: firefox/' -i debian/control.in

debian/rules debian/control
touch -d "yesterday" debian/control
debian/rules debian/control

changelog  "Rebranded for Trisquel"

package
