#!/bin/bash
#
#    Copyright (C) 2025  Luis Guzmán <ark@switnet.org>
#    Copyright (C) 2020  Ruben Rodriguez <ruben@trisquel.info>
#    Copyright (C) 2019  David Trudgian <dave@trudgian.net>
#
#    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=23
EXTERNAL='deb-src http://ppa.launchpadcontent.net/mozillateam/ppa/ubuntu $UPSTREAM main'
REPOKEY=9BDB3D89CE49EC21

. ./config

# Get initial SHA256 hashes.
SHA256_F1=$(sha256sum third_party/cbindgen/vendor/winnow/examples/http/main.rs|awk '{print$1}')
SHA256_F2=$(sha256sum third_party/cbindgen/vendor/winnow/examples/http/bench.rs|awk '{print$1}')
SHA256_F3=$(sha256sum third_party/dump_syms/vendor/httparse/benches/parse.rs|awk '{print$1}')
SHA256_F4=$(sha256sum third_party/dump_syms/vendor/httparse/src/lib.rs|awk '{print$1}')
SHA256_F5=$(sha256sum third_party/dump_syms/vendor/hyper-rustls/src/connector/builder.rs|awk '{print$1}')
SHA256_F6=$(sha256sum third_party/dump_syms/vendor/rustls/src/lib.rs|awk '{print$1}')
SHA256_F7=$(sha256sum third_party/dump_syms/vendor/rustls-webpki/src/subject_name/dns_name.rs|awk '{print$1}')
SHA256_F8=$(sha256sum third_party/dump_syms/vendor/rustls-webpki/src/verify_cert.rs|awk '{print$1}')
SHA256_F9=$(sha256sum comm/third_party/rust/glean/src/configuration.rs|awk '{print$1}')

# Copy in our local Trisquel branding files.
cp $DATA/branding/* comm/mail/branding/nightly/ -r
cp $DATA/branding/* comm/mail/branding/thunderbird/ -r
#for i in aurora nightly official unofficial; do
#  cp $DATA/branding/* browser/branding/$i/ -r
#done

# Privacy and branding via prefs
cat << EOF >> debian/vendor.js

// Trisquel settings
pref("app.releaseNotesURL", "http://trisquel.info/wiki/Icedove");
pref("app.vendorURL", "http://trisquel.info/wiki/Icedove");

// PFS url
pref("pfs.datasource.url", "https://trisquel.info/sites/pfs.php?mime=%PLUGIN_MIMETYPE%");
pref("pfs.filehint.url", "https://trisquel.info/sites/pfs.php?mime=%PLUGIN_MIMETYPE%");

// DuckDuckGo
pref("keyword.URL", "https://duckduckgo.com/?t=trisquel&q=!+");
pref("browser.search.defaultenginename", "DuckDuckGo");
pref("browser.search.order.1", "DuckDuckGo");
pref("browser.search.defaultenginename", "DuckDuckGo");
pref("browser.search.showOneOffButtons", false);
pref("browser.search.suggest.enabled",false);

// Disable third party cookies
pref("network.cookie.cookieBehavior", 1);

// Extensions cannot be updated without permission
pref("extensions.update.enabled", false);
pref("extensions.systemAddon.update.enabled", false);
pref("lightweightThemes.update.enabled", false);

// Don't show suggested provider list
pref("mail.provider.enabled", false);
pref("mail.provider.providerList", "");
pref("mail.provider.suggestFromName", "");

// Don't prompt if not default mail client
pref("mail.shell.checkDefaultClient", false);

// Preferences for the Get Add-ons panel
pref("extensions.webservice.discoverURL", "https://directory.fsf.org/wiki/Icedove");
pref("extensions.getAddons.search.url", "https://trisquel.info");
pref("extensions.blocklist.enabled", false);

// Dictionary download preference
pref("spellchecker.dictionaries.download.url", "http://dictionaries.mozdev.org/installation.html");

// Privacy protections
pref("mail.rights.version", 1);
pref("toolkit.telemetry.prompted", 2);
pref("toolkit.telemetry.rejected", true);
pref("mailnews.start_page.enabled", false);
pref("mailnews.start_page.url", "");
pref("mailnews.start_page.override_url", "");
pref("app.update.auto", false);
pref("app.update.enabled", false);
pref("browser.search.update", false);

pref("app.update.url.manual", "https://trisquel.info/wiki/icedove");
pref("mail.cloud_files.inserted_urls.footer.link", "https://trisquel.info/wiki/icedove");
pref("mail.cloud_files.learn_more_url", "https://trisquel.info/wiki/icedove");
pref("mail.ignore_thread.learn_more_url", "https://trisquel.info/wiki/icedove");
pref("mail.pgpmime.addon_url", "https://enigmail.net/");
pref("app.support.baseURL", "https://trisquel.info/wiki/icedove");
pref("app.update.url.manual", "https://trisquel.info/wiki/icedove");
// Send to the Icedove wiki as we have no addon store to recommend
pref("extensions.getAddons.link.url", "https://trisquel.info/wiki/icedove");
pref("extensions.getAddons.search.browseURL", "https://trisquel.info/en/browser-plain?keys=%TERMS%&tid=All");
pref("extensions.getAddons.search.url", "https://trisquel.info/en/browser-plain?keys=%TERMS%&tid=All");

// Disable telemetry pings to enhance privacy.
pref("toolkit.telemetry.archive.enabled", false);
pref("toolkit.telemetry.unified", false);
pref("toolkit.telemetry.updatePing.enabled", false);
pref("toolkit.telemetry.shutdownPingSender.enabled", false);
pref("toolkit.telemetry.newProfilePing.enabled", false);
pref("toolkit.telemetry.firstShutdownPing.enabled", false);
pref("toolkit.telemetry.bhrPing.enabled", false);
pref("browser.ping-centre.telemetry", false);
pref("dom.security.unexpected_system_load_telemetry_enabled", false);

EOF

# DDG as default search engine
sed 's/?q=/?t=trisquel&q=/' -i comm/mail/components/search/extensions/ddg/manifest.json
sed '/searchDefault/s/: \".*\"/: "DuckDuckGo"/g' -i comm/mail/components/search/extensions/list.json
sed '/visibleDefaultEngines/{n; s/"ddg",//; s/\"/"ddg", "/}'  -i comm/mail/components/search/extensions/list.json

# ####################################################
# Privacy / branding brought in from abrowser for 60.x
#
# captive portal page
sed '/captivedetect.canonicalURL/s/http.*.html//' -i modules/libpref/init/all.js
# do not alter useragent/platform/oscpu/etc with fingerprinting countermeasure, it makes things worse
sed '/ (aShouldResistFingerprinting/,/}/s/^/\/\//' -i ./netwerk/protocol/http/nsHttpHandler.cpp
sed '/If fingerprinting resistance is on/,/}/s/^/\/\//' -i ./dom/base/Navigator.cpp
# 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
#cp toolkit/components/telemetry/healthreport-prefs.js mobile/android/chrome/content/healthreport-prefs.js
# Browser legal page
sed 's%https://www.mozilla.org/legal/privacy/%https://trisquel.info/legal%' -i ./browser/app/profile/firefox.js ./toolkit/content/aboutRights.xhtml
sed -i 's|https://www.mozilla.org/thunderbird/legal/privacy/|https://trisquel.info/legal|' comm/mail/app/profile/all-thunderbird.js
sed -i 's|https://www.mozilla.org/en-US/privacy/thunderbird/|https://trisquel.info/legal|' comm/mail/app/profile/all-thunderbird.js
sed -i 's|https://www.mozilla.org/privacy/thunderbird/|https://trisquel.info/legal|' comm/mail/components/accountcreation/content/accountSetup.xhtml
grep -rl https://www.mozilla.org/privacy/thunderbird/ | xargs -r sed -i 's|https://www.mozilla.org/privacy/thunderbird/|https://trisquel.info/legal|g'

# 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|'
grep -rl browser.ping-centre.telemetry | xargs -r sed -i '/browser.ping-centre.telemetry/s|true|false|'
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|'
grep -rl '"datareporting.healthreport.uploadEnabled"'| xargs -r sed -i '/"datareporting.healthreport.uploadEnabled"/s|[Tt]rue|false|'
grep -rl '"datareporting.policy.dataSubmissionEnabled"'| xargs -r sed -i '/"datareporting.policy.dataSubmissionEnabled"/s|[Tt]rue|false|'
echo 'pref("dom.security.unexpected_system_load_telemetry_enabled", false);' | tee -a browser/app/profile/firefox.js
echo 'pref("toolkit.telemetry.hybridContent.enabled", false);' | tee -a browser/app/profile/firefox.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 != armhf
%%if DEB_HOST_ARCH != arm64
%%if DEB_HOST_ARCH != ppc64el
ac_add_options --disable-eme
%%endif
%%endif
%%endif
ARCH
########################################################
sed '/^MOZ_PKG_NAME/s/.*/MOZ_PKG_NAME=icedove/' -i debian/build/config.mk

cat << EOF >> debian/build/config.mk

# Trisquel settings
MOZ_FORCE_UNOFFICIAL_BRANDING = 1
MOZ_WANT_UNIT_TESTS = 0
MOZ_ENABLE_BREAKPAD = 0
EOF

# Replace Thunderbird branding
find -type d -name '*thunderbird*' | xargs rename s/thunderbird/icedove/
find -type f -name '*thunderbird*' | xargs rename s/thunderbird/icedove/

SEDSCRIPT="
s|Search addons.mozilla.org|Search|g;
s/Mozilla Thunderbird/Icedove/g;
s/thunderbird/icedove/g;
s/Thunderbird/Icedove/g;
s/THUNDERBIRD/ICEDOVE/g;
s/ Mozilla / Trisquel /g;
s/Firefox/Abrowser/g;
s|PACKAGES/icedove|PACKAGES/thunderbird|g;
s/iceweasel, icedove/iceweasel, thunderbird/g;
s/Replaces: icedove/Replaces: thunderbird/g;
s|www.mozilla.com/icedove/central|trisquel.info/browser|g;
s|mozilla.com/plugincheck|trisquel.info/browser|g;
s|www.mozilla.com/legal/privacy|trisquel.info/legal|g;

s/Trisquel Public/Mozilla Public/g;
s/Trisquel Foundation/Mozilla Foundation/g;
s/Trisquel Corporation/Mozilla Corporation/g;
s|this-firefox|this-abrowser|g;
"
echo "Running batch replace operation"
find . -type f \
    -not -iregex '.*changelog.*' \
    -not -iregex '.*copyright.*' \
    -not -iregex '.*third_party/rust.*' \
    -not -iregex '.*comm/rust.*' \
    -execdir /bin/sed --follow-symlinks -i "$SEDSCRIPT" '{}' ';'

# Fix wrong changes, restore changes to reduce diff with previous sed script.
grep -rl "Trisquel Bug" | xargs -r sed -i "s| Trisquel Bug | Mozilla Bug |g"
grep -rl "AbrowserGraphics" | xargs -r sed -i "/github/s|AbrowserGraphics|FirefoxGraphics|g"
grep -rl IcedoveProfileImporter. | xargs -r sed -i 's|IcedoveProfileImporter|ThunderbirdProfileImporter|g'
grep -rl IcedoveProfileMigrator | xargs -r sed -i 's|IcedoveProfileMigrator|ThunderbirdProfileMigrator|g'
grep -rl AbrowserViewTestUtils | xargs -r sed -i 's|AbrowserViewTestUtils|FirefoxViewTestUtils|g'
grep -rl AbrowserRelay | xargs -r sed -i 's|AbrowserRelay|FirefoxRelay|g'
sed -i '/TB_/s|mozilla-icedove|mozilla-thunderbird|' debian/rules
#Fix 1 character bigger than allowed yml line (81 > 80)
sed -i "s|Abrowser is not running.  It|Abrowser isn't running. It|" toolkit/mozapps/update/pings.yaml
sed -i '/Certificate data/s|Trisquel|Mozilla|' third_party/dump_syms/vendor/webpki-roots/LICENSE

# Set main links - check comm/mailnews/base/content/msgAccountCentral.xhtml for main class & id links.
grep -rl 'https://www.icedove.net/participate/' comm/ | xargs -r sed -i 's|https://www.icedove.net/participate/|https://trisquel.info/wiki/|'
grep -rl 'https://www.icedove.net/donate/' comm/ | xargs -r sed -i 's|https://www.icedove.net/donate/.*"|https://trisquel.info/donate/"|'
grep -rl 'https://www.icedove.net/donate/' comm/ | xargs -r sed -i 's|https://www.icedove.net/donate/|https://trisquel.info/donate/|'
grep -rl 'https://updates.icedove.net/icedove/' comm/ | xargs -r sed -i '/app.donation.eoy.url/s|https://updates.icedove.net/icedove/.*"|https://trisquel.info/donate/"|'
grep -rl 'https://support.mozilla.org/products/icedove' comm/ | xargs -r sed -i 's|https://support.mozilla.org/products/icedove.*"|https://trisquel.info/wiki/icedove"|'
grep -rl 'https://support.mozilla.org/products/icedove' comm/ | xargs -r sed -i 's|https://support.mozilla.org/products/icedove/|https://trisquel.info/wiki/icedove/|'
grep -rl 'https://developer.icedove.net/' comm/ | xargs -r sed -i 's|https://developer.icedove.net/|https://gitlab.trisquel.org/trisquel/package-helpers|'

replace Daily Trisquel comm/mail/branding/
# Remove Thunderbird branding
sed '/.*<div.*communityExperimentalDesc/,/\/div/d' -i ./comm/mail/base/content/aboutDialog.xhtml
sed '/.*<div.*communityDesc/,/\/div/d' -i ./comm/mail/base/content/aboutDialog.xhtml
sed '/.*<div.*contributeDesc/,/\/div/d' -i ./comm/mail/base/content/aboutDialog.xhtml

# Apply debian/control.in changes.
sed '/^Source/s/.*/Source: thunderbird/' -i debian/control.in
sed 's/Provides: mail-reader,/Provides: mail-reader, thunderbird,/' -i debian/control.in
sed "s/Provides.*/Provides: icedove-locale-@LANGCODE@/" -i debian/control.langpacks

# Set and replace sha256 checksums to match our changes.
SHA256_F1_MOD=$(sha256sum third_party/cbindgen/vendor/winnow/examples/http/main.rs|awk '{print$1}')
SHA256_F2_MOD=$(sha256sum third_party/cbindgen/vendor/winnow/examples/http/bench.rs|awk '{print$1}')
SHA256_F3_MOD=$(sha256sum third_party/dump_syms/vendor/httparse/benches/parse.rs|awk '{print$1}')
SHA256_F4_MOD=$(sha256sum third_party/dump_syms/vendor/httparse/src/lib.rs|awk '{print$1}')
SHA256_F5_MOD=$(sha256sum third_party/dump_syms/vendor/hyper-rustls/src/connector/builder.rs|awk '{print$1}')
SHA256_F6_MOD=$(sha256sum third_party/dump_syms/vendor/rustls/src/lib.rs|awk '{print$1}')
SHA256_F7_MOD=$(sha256sum third_party/dump_syms/vendor/rustls-webpki/src/subject_name/dns_name.rs|awk '{print$1}')
SHA256_F8_MOD=$(sha256sum third_party/dump_syms/vendor/rustls-webpki/src/verify_cert.rs|awk '{print$1}')
SHA256_F9_MOD=$(sha256sum comm/third_party/rust/glean/src/configuration.rs|awk '{print$1}')

sed_csum $SHA256_F1 $SHA256_F1_MOD
sed_csum $SHA256_F2 $SHA256_F2_MOD
sed_csum $SHA256_F3 $SHA256_F3_MOD
sed_csum $SHA256_F4 $SHA256_F4_MOD
sed_csum $SHA256_F5 $SHA256_F5_MOD
sed_csum $SHA256_F6 $SHA256_F6_MOD
sed_csum $SHA256_F7 $SHA256_F7_MOD
sed_csum $SHA256_F8 $SHA256_F8_MOD
sed_csum $SHA256_F9 $SHA256_F9_MOD
#EO Manual fixing.

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

for STRING in rights-intro-point-2 rights-intro-point-3 rights-intro-point-4 rights-intro-point-5 rights-intro-point-6 rights-webservices rights-safebrowsing
do
 find -name aboutRights.ftl | xargs -r sed -i "s/^$STRING.*/$STRING = /"
done
##Remove invalid policy for trisquel, make sure to check for changes on
##each release as they silently update and change.
find -name aboutRights.ftl | xargs -r sed -i '/rights-intro-point-3/,/li>/d'
find -name aboutRights.xhtml |xargs -r sed -i "/rights-intro-point-5/,/li>/d"
find -name aboutRights.xhtml |xargs -r sed -i "/rights-intro-point-6/d"
find -name aboutRights-unbranded.xhtml |xargs -r sed -i "/rights-intro-point-5/,/li>/d"

sed -i 's/<a\ href\=\"https\:\/\/www.icedove.net\/\">Icedove\ Project<\/a>/<a\ href\=\"https\:\/\/www.trisquel.info\/\"\>Trisquel\ Project<\/a>/g' \
    comm/mail/base/content/overrides/app-license.html
#EO about: mods.

#Rebrand debug tools
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

cp $DATA/debug_brand/about-logo.svg comm/mail/branding/icedove/TB-symbolic.svg
cp $DATA/debug_brand/about-logo.svg comm/mail/themes/shared/mail/icons/aboutdebugging-logo.svg
cp $DATA/debug_brand/icon.png    comm/mail/themes/icon.png
cp $DATA/debug_brand/icon64.png  comm/mail/themes/icon64.png
cp $DATA/debug_brand/account-watermark*.png comm/mail/themes/shared/mail/images/

#Requirements for Icedove
THNDR_SYS_URL="https://www.icedove.net/icedove/system-requirements/"
ICEDV_SYS_URL="https://trisquel.info/wiki/icedove-requirements/"
sed -i "s|$THNDR_SYS_URL|$ICEDV_SYS_URL|" comm/mail/branding/icedove/branding.nsi

#Remove search engines inherited from firefox (remove all?).
for r in amazon amazondotcn amazondotcom bing google mercadolibre mercadolivre yahoo-jp yahoo-jp-auctions
do
    rm -r comm/mail/components/search/extensions/$r
done

for r2 in amazon bing google yahoo
do
    find comm/suite -name $r2* -delete
done

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

#EO Debbuging tools

cat << EOF > comm/mail/branding/nightly/locales/en-US/brand.properties
brandShortName=Icedove
brandShorterName=Icedove
brandFullName=Icedove Mail
vendorShortName=Icedove
EOF

BRAND_FTL_NTLY=comm/mail/branding/nightly/locales/en-US/brand.ftl
BRAND_FTL_STD=comm/mail/branding/icedove/locales/en-US/brand.ftl
sed -i '/shorter-name/s|Trisquel|Icedove|' $BRAND_FTL_NTLY
sed -i '/short-name/s|Trisquel|Icedove|' $BRAND_FTL_NTLY
sed -i '/full-name/s|Icedove Trisquel|Icedove Mail|' $BRAND_FTL_NTLY
sed -i '/full-name/s|Icedove|Icedove Mail|' $BRAND_FTL_STD

# Clean brand from export to mobile title & rm android app recommendation - l10n
# qr-export-get-app removed via patch.
patch_p1 $DATA/patches_changes/001-set_export_to_mobile_l10n.patch
grep -lr "qr-export-pane-header ="|xargs -r sed -i '/^qr-export-pane-header =/s| { -brand-product-name[^}]*}||g'
grep -rl 'qr-export-no-accounts =' | xargs -r sed -i '/^qr-export-no-accounts =/ {
    s|{ -brand-product-name }||g;
    s| by  for | for |g;
    s| supported by  for | supported for |g
}'

cat << EOF > comm/mail/branding/nightly/locales/en-US/brand.dtd
<!-- This Source Code Form is subject to the terms of the Mozilla Public
   - License, v. 2.0. If a copy of the MPL was not distributed with this
   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->

<!ENTITY  brandShortName        "Icedove">
<!ENTITY  brandShorterName      "Icedove">
<!ENTITY  brandFullName         "Icedove Mail">
<!-- LOCALIZATION NOTE (brandProductName):
   This brand name can be used in messages where the product name needs to
   remain unchanged across different versions (Trisquel, Beta, etc.). -->
<!ENTITY  brandProductName      "Icedove">
<!ENTITY  vendorShortName       "mozilla.org">
<!ENTITY  trademarkInfo.part1   " ">
EOF

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

changelog  "Rebranded for Trisquel"

package
