#!/bin/sh
# Copyright (C) 2023 Denis 'GNUtoo' Carikli <GNUtoo@cyberdimension.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 3 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, see <https://www.gnu.org/licenses/>.
set -e

arch="$(gcc -dumpmachine | sed 's/-.*//')"
arguments=""

expose()
{
    local path="$1"

    if [ -e "${path}" ] ; then
        arguments="${arguments} --expose=${path}"
    fi
}

guix_shell_tor_browser()
{
    expose "/tmp/.X1-lock"
    expose "/tmp/.X11-unix"

    expose "${XAUTHORITY}"

    # I have my Download folder somewhere else. Right now it's on another
    # partition. And I want tor-browser to use that folder for storing
    # Downloads. For that to work we need to give the tor-browser write access
    # to it. Other methods were tried but didn't work:
    # - mounting the real Download path  to Downloads resulted in the
    #   tor-browser failing to start.
    # - Using
    #   --exporse=/real/path/to/Downloads=${HOME}/.../Browser/Downloads
    #   did not work either because Download was unaccessible. Replacing
    #   --expose by share in the command above didn't change anything.
    # So I ended up using --share=/path/to/real/Downloads.
    # That requires the user to do the symlink manually though.

    local shares=""
    if [ -L "Downloads" ] ; then
        local downloads="$(realpath "$(readlink Downloads)")"
        shares=--share="${downloads}"
    fi

    # We cannot pass an empty variables like that to guix shell:
    #     $ guix shell "" bash -- bash
    #     guix shell: error: : unknown package
    # so since arguments is always set, we need to add "${shares}" to it
    # instead in the case where Download isn't a symlink.
    if [ -n "${shares}" ] ; then
        arguments="${arguments} ${shares}"
    fi

    guix shell \
         --preserve="^DISPLAY$" \
         --preserve="^XAUTHORITY$" \
         --container \
         --emulate-fhs \
         --network \
         ${arguments} \
         -e '(list (@@ (gnu packages commencement) gcc-final) "lib")' \
         alsa-lib \
         bash \
         coreutils \
         dbus-glib \
         file \
         grep \
         gtk+@3 \
         libxt \
         sed \
         -- \
         bash -l -c "./start-tor-browser $@"
}

start_tor_browser()
{
    cd "${HOME}/.local/share/torbrowser/tbb/${arch}/tor-browser/Browser/"
    guix_shell_tor_browser
}

start_tor_browser
