#!/bin/sh
#
#    Copyright (C) 2011-2023  Ruben Rodriguez <ruben@trisquel.info>
#    Copyright (C)      2019  Mason Hock <mason@masonhock.com>
#
#    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=34

. ./config

# Disable confirmation popups, as they are innacurate and buggy
patch --no-backup-if-mismatch -p1 < $DATA/no_confrirmation_when_crypto.patch

# Fix some gtk labels for Orca
patch --no-backup-if-mismatch -p1 < $DATA/a11y.patch

# Point ubiquity crash to trisquel's forge.
patch --no-backup-if-mismatch -p1 < $DATA/crash_report_point_to_trisquel_forge.patch

# Remove test_timezone to prevent error out future builds on different daylight time.
rm tests/test_timezone.py

# Revert changes to advanced features page
cp $DATA/stepPartAsk.ui gui/gtk/stepPartAsk.ui
sed '/# Advanced features in new installs/,/^$/d' -i ubiquity/plugins/ubi-partman.py

# Do not try to start orca on ubiquity-dm
sed 's/osextras.find_on_path.*orca.*/False:  # Disabled by trisquel changes/' -i bin/ubiquity-dm

# Disable non-main repository handling
sed 's/main.*//' -i autopilot/ubiquity-autopilot-runner/custom-installation/iso-override/etc/apt/sources.list.d/all.list
sed '/universe multiverse/d' -i bin/oem-config-remaster

# Use standard monospaced font for console
sed 's/Ubuntu Mono/Monospace Regular/' -i ubiquity/frontend/gtk_ui.py

# Start a11y-profile-manager-indicator only if not running already
sed "/if osextras.find_on_path..a11y-profile-manager-indicator/s/:/ and (subprocess.run(\n                ['pgrep', '-f', 'a11y-profile-manager-indicator'], capture_output=True).returncode == 0):/" -i ubiquity/frontend/gtk_ui.py

# Fixes issues starting orca
sed "/Popen/s/'orca'/'orca', '--replace'/" -i ubiquity/frontend/gtk_ui.py

# Kill at-spi after maybe-ubiquity, allows a11y to work on live desktop installer
sed "/signal.alarm(0)/a\ \ \ \ \ \ \ \ subprocess.call\(['pkill', '-9', 'at-spi'], stdin=null, stdout=logfile, stderr=logfile)" -i bin/ubiquity-dm

cp $DATA/trisquel_installed.png pixmaps
rm pixmaps/ubuntu_installed.png
replace ubuntu_installed trisquel_installed .

replace linux-signed linux-lowlatency .
replace shim-signed shim .
replace grub-efi-amd64-signed grub-efi-amd64 .

/bin/sed '/canonical/d' -i debian/ubiquity.install*
rm  tests/test_ubi_partman*

#sed -i '0,/ubuntu-artwork/{/ubuntu-artwork/d;}' debian/control

export DEB_BUILD_OPTIONS=nocheck

# Fix update issues on clean installations: https://trisquel.info/es/forum/update-issues-clean-install
sed 's:\(targetdb)\):\1\n        os.system("sudo chmod 644 /target/var/cache/debconf/config.dat"):' bin/ubiquity -i

# Fix https://bugs.launchpad.net/ubuntu/+source/ubiquity/+bug/1080701
sed '/from ubiquity import osextras/s/$/\nos.system("sudo swapoff -a")/' bin/ubiquity-wrapper -i

for i in $(ls -1 d-i/source/apt-setup/generators |grep -v 01setup|grep -v 40cdrom) canonical.com security.ubuntu.com extras.ubuntu.com
do
    /bin/sed /$i/d -i debian/ubiquity.install-any d-i/source/apt-setup/debian/*.install
done
echo "d-i/source/apt-setup/generators/99trisquel usr/lib/ubiquity/apt-setup/generators" >> debian/ubiquity.install-any

#change icon
cp $DATA/trisquel.png data/ubiquity.png

# remove Ubuntu apt setup for the installer
find d-i/source/apt-setup/generators -type f | grep -v 01setup |grep -v 40cdrom| xargs -r rm
cat << EOF1 > d-i/source/apt-setup/generators/99trisquel
#!/bin/sh
set -e

file="\$1"

FASTEST=https://archive.trisquel.org/trisquel/
SPEED=1000000000000

if nm-online -xq
then
    for i in \$(grep '//' /usr/share/python-apt/templates/Trisquel.mirrors | sed 's|/$||')
    do
        echo Testing \$i
        TIME=\$(date +%s%N)
        wget --no-check-certificate -t 1 -T 5 --max-redirect=0 -o /dev/null -O /dev/null \$i/speedtest || continue
        TIME2=\$(date +%s%N)
        ELAPSED=\$(expr \$TIME2 - \$TIME)
        echo Time: \$ELAPSED
        if [ \$ELAPSED -lt \$SPEED ]
        then
            FASTEST=\$i
            SPEED=\$ELAPSED
        fi
    done
fi

echo "Selected mirror: \$FASTEST"

MIRROR=\$FASTEST
RELEASE=\$(lsb_release -c | cut -f 2)

cat << EOF > \$file
# Trisquel repositories for supported software and updates
deb \$MIRROR \$RELEASE main
deb-src \$MIRROR \$RELEASE main
deb \$MIRROR \$RELEASE-security main
deb-src \$MIRROR \$RELEASE-security main
deb \$MIRROR \$RELEASE-updates main
deb-src \$MIRROR \$RELEASE-updates main
#deb \$MIRROR \$RELEASE-backports main
#deb-src \$MIRROR \$RELEASE-backports main
EOF
EOF1
chmod 755 d-i/source/apt-setup/generators/99trisquel

# Redirect ports.ubuntu.com
sed '/ports.ubuntu.com/d' -i ./d-i/source/apt-setup/debian/apt-mirror-setup.install
sed 's/ports.ubuntu.com/archive.trisquel.org/g; s/ubuntu-ports/trisquel/g; s/ubuntu/trisquel/g' -i ./d-i/source/apt-setup/debian/rules ./d-i/source/base-installer/library.sh
sed 's/CC.ports.ubuntu.com/archive.trisquel.org/g; s/.ports.ubuntu.com/archive.trisquel.org/g' -i ./d-i/source/choose-mirror/choose-mirror.c ./d-i/source/choose-mirror/debian/choose-mirror-bin.templates.ftp.sel-in ./d-i/source/choose-mirror/debian/choose-mirror-bin.templates.http-in

# Set Mirrors.masterlist
wget https://archive.trisquel.org/trisquel/Mirrors.masterlist -O ./d-i/source/choose-mirror/Mirrors.masterlist
sed '/Location/d; /Comment/d;' -i ./d-i/source/choose-mirror/Mirrors.masterlist
cp ./d-i/source/choose-mirror/Mirrors.masterlist ./d-i/source/choose-mirror/Mirrors.masterlist.trisquel
rm ./d-i/source/choose-mirror/Mirrors.masterlist.ubuntu
sed 's/Mirrors.masterlist.ubuntu/Mirrors.masterlist/' -i  d-i/source/choose-mirror/Makefile

# Set apt-mirror-setup.templates
cat << EOF > d-i/source/apt-setup/debian/apt-mirror-setup.templates-ubuntu
Template: apt-setup/restricted
Type: boolean
Default: false

Template: apt-setup/backports
Type: boolean
Default: true
# This template is used by the Trisquel version of d-i.
# :sl2:
_Description: Use backported software?
 Some software has been backported from the development tree to work with
 this release. Although this software has not gone through such complete
 testing as that contained in the release, it includes newer versions of
 some applications which may provide useful features.
 .
 Please choose whether you want this software to be made available to you.
EOF
mv d-i/source/apt-setup/debian/apt-mirror-setup.templates-ubuntu d-i/source/apt-setup/debian/apt-mirror-setup.templates-trisquel

cat << EOF > d-i/source/apt-setup/debian/apt-mirror-setup.templates
Template: apt-setup/progress/mirror
Type: text
# :sl1:
_Description: Scanning the mirror...

Template: apt-setup/mirror/error
Type: select
Default: Retry
# :sl2:
# These are choices of actions so this is, at least in English,
# an infinitive form
__Choices: Retry, Change mirror, Ignore
_Description: Downloading a file failed:
 The installer failed to access the mirror. This may be a problem with your
 network, or with the mirror. You can choose to retry the download, select
 a different mirror, or ignore the problem and continue without all the
 packages from this mirror.

# Default is determined in mirror generators!
Template: apt-setup/use_mirror
Type: boolean
# :sl1:
#flag:translate!:3
_Description: Use a network mirror?
 A network mirror can be used to supplement the software that is included
 on the CD-ROM. This may also make newer versions of software available.
 .
 \${EXPLANATION}

Template: apt-setup/no_mirror
Type: boolean
Default: false
# :sl2:
_Description: Continue without a network mirror?
 No network mirror was selected.
 .
 If you are installing from a netinst CD and choose not to use a mirror,
 you will end up with only a very minimal base system.
EOF

# Rebrand
replace $UPSTREAM $CODENAME .
replace Ubuntu Trisquel .
replace Kubuntu Triskel .
replace kubuntu triskel .
find | grep kubuntu.*svg | xargs rename s/kubuntu/triskel/
replace Trisquel-Gettext-Domain Ubuntu-Gettext-Domain
## rebrand l18n
  ## Korean - Fix #27659
replace 우분투 Trisquel .
#replace triskel-ubiquity kubuntu-ubiquity
replace "https://bugs.launchpad.net/ubuntu/+source/.*/+bug/" "LP:#" .
replace "https://git.launchpad.net/ubuntu/+source/" "https://gitlab.trisquel.org/trisquel/" .
replace "launchpad.net/ubuntu/+source/ubiquity/+filebug" "gitlab.trisquel.org/trisquel/package-helpers/-/issues" .
replace "ubiquity/+filebug" "" .
replace "+filebug" "" .
replace " ubuntu/devel$" "" .
replace archive.ubuntu.com/ubuntu archive.trisquel.org/trisquel .
replace security.ubuntu.com/trisquel archive.trisquel.org/trisquel .
replace archive.ubuntu.com archive.trisquel.org .
replace security.ubuntu.com archive.trisquel.org .
replace help.ubuntu.com/bitlocker trisquel.info/en/wiki/bitlocker .
#sed -i 's/apt-install/true #apt-install/' ubiquity/components/check_kernels.py
sed -i 's/apt-install/true #apt-install/' scripts/check-kernels
#sed -i '82s/True/False/g' gui/gtk/stepPrepare.ui

rm -rf d-i/source/apt-setup/release-files/*
for DIST in $CODENAME $CODENAME-security $CODENAME-updates $CODENAME-backports
do
    WD=d-i/source/apt-setup/release-files/archive.trisquel.org/$DIST
    mkdir $WD -p
    wget -r -l1 -np https://archive.trisquel.org/trisquel/dists/$DIST/Release -O $WD/Release
    wget -r -l1 -np https://archive.trisquel.org/trisquel/dists/$DIST/Release.gpg -O $WD/Release.gpg
done

cp $DATA/branding.svgz gui/qt/images/branding.svgz

# Postinstall hacks
cat << EOF1 >> scripts/apt-setup

#Trisquel hack to regenerate ssl keys after installation
if [ -f /target/etc/ssh/ssh_host_rsa_key ]; then
    rm -f /target/etc/ssh/ssh_host_*
    ssh-keygen -q -f /target/etc/ssh/ssh_host_rsa_key -N '' -t rsa
    ssh-keygen -q -f /target/etc/ssh/ssh_host_dsa_key -N '' -t dsa
fi
if [ -d /etc/italc ]
then
    rm -rf /etc/italc/*
    /usr/bin/ica -role teacher -createkeypair >/dev/null
    /usr/bin/ica -role admin -createkeypair >/dev/null
    /usr/bin/ica -role supporter -createkeypair >/dev/null

    rm /target/etc/italc/ -rf
    cp /etc/italc/ /target/etc/ -a

    chown root:admin /target/etc/italc/keys/private/*/key
fi

# Hacks for accessibility
if [ \$(su trisquel -c "gsettings get org.mate.applications-at screen-reader-enabled") = "true" ] || \
   [ \$(su trisquel -c "gsettings get org.gnome.desktop.a11y.applications screen-reader-enabled") = "true" ]
then
  echo "Accessibility profile set to 'blindness', enabling screen reader by default in target system"
  echo "[org.mate.applications-at]
screen-reader-enabled=true

[org.mate.applications-at-visual]
startup=true

[org.mate.desktop.interface]
accessibility=true

[org.gnome.desktop.a11y.applications]
screen-reader-enabled=true

[org.gnome.desktop.interface]
toolkit-accessibility=true

[com.canonical.unity-greeter]
screen-reader=true
" >> /target/usr/share/glib-2.0/schemas/99_accessibility.gschema.override
  chroot /target glib-compile-schemas /usr/share/glib-2.0/schemas

  if grep -q lightdm /target/etc/passwd; then
    mkdir -p /target/var/lib/lightdm/.cache/lightdm-gtk-greeter/
    echo "[a11y-states]
    reader=true" > /target/var/lib/lightdm/.cache/lightdm-gtk-greeter/state
    chroot /target chown lightdm.lightdm /var/lib/lightdm/ -R
    chmod 750 /target/var/lib/lightdm/
  fi

else 
  echo "Accessibility profile set to none, disabling screen reader by default in target system"
  rm /target/home/*/.local/share/orca/user-settings.conf -f
fi

EOF1

# Fix dependency for triskel
sed '/Package: ubiquity-frontend-kde/,/Depends/s/Depends:/Depends: libkf5kdelibs4support5-bin,/' -i debian/control

sed 's/Trisquel/Trsql/' -i ubiquity/plugins/ubi-partman.py
sed 's/Trisquel-Battersea/Ubuntu-Battersea/' -i  tests/test_gtkwidgets.py

# Remove ubuntu-artwork dependency
sed -i '/ubuntu-artwork,/d' debian/control

# Only warn about missing efi partition when running on efi mode
sed 's|/var/lib/partman/efi|/sys/firmware/efi|' -i d-i/source/partman-efi/check.d/efi

changelog "Adapted for Trisquel"

rm -rf debian/source

compile
