#!/usr/bin/env bash
# @file Post Installation Tasks
# @brief Executes logic meant to be run after the user's software preferences are installed.
# @description
#     This script performs various tasks meant to be run after the user's specified applications are
#     installed.

{{ includeTemplate "universal/profile" }}
{{ includeTemplate "universal/logg" }}

# @description
#     This script ensures Bash is configured to use Bash It! It ensures dependencies are installed, installs completions,
#     and enables Bash It! plugins. The completions and plugins are hardcoded in this script. Source file might need `#!/usr/bin/env -S bash -i`.
bashItPlugins() {
  ### Ensure Powerline is installed
  if ! command -v powerline > /dev/null; then
    logg info 'Installing powerline via install-program'
    install-program powerline > /dev/null
  fi

  ### Include Bash It
  export BASH_IT="${XDG_DATA_HOME:-$HOME/.local/share}/bash_it"
  export BASH_IT_THEME="powerline"
  if command -v powerline-daemon > /dev/null && [ -f "$BASH_IT/bash_it.sh" ] && ! command -v bash-it; then
    logg info "Sourcing the bash_it.sh script"
    . "$BASH_IT/bash_it.sh"
  fi

  ### Ensure ble.sh installed
  if [ -d "${XDG_DATA_HOME:-$HOME/.local/share}/blesh/src" ]; then
    logg info 'Make installing blesh'
    make -C "${XDG_DATA_HOME:-$HOME/.local/share}/blesh/src" install > /dev/null && logg info "Installed ble.sh" || logg error "Error running make -C "${XDG_DATA_HOME:-$HOME/.local/share}/blesh/src" install"
  fi

  ### Bash-it completions / plugins
  if command -v powerline > /dev/null && [ -f "$HOME/.bashrc" ]; then
    if [ -d "$BASH_IT" ]; then
      ### Ensure bash-it is installed
      if ! command -v bash-it > /dev/null; then
        logg info 'Installing bash-it since it is not available yet as a command'
        bash "$BASH_IT/install.sh" --silent --no-modify-config
      else
        logg info 'bash-it already available'
      fi

      ### Ensure completions are enabled
      if [ ! -d "$BASH_IT/enabled" ]; then
        logg info "Creating the $BASH_IT/enabled directory" && mkdir -p "$BASH_IT/enabled"
      fi
      logg info "Changing directory to $BASH_IT/enabled" && cd "$BASH_IT/enabled"
      logg info 'Enabling bash-it completions'
      # TODO: Move these plugins to the .chezmoidata.yaml
      for COMPLETION in defaults dirs docker docker-compose export git makefile ng ssh system vagrant; do
        if ls "$BASH_IT/enabled" | grep "$COMPLETION" > /dev/null; then
          rm -f "$BASH_IT/enabled/"*"$COMPLETION"* > /dev/null && logg info "Removed old $COMPLETION bash-it completion symlink" || logg error "Failed to remove $COMPLETION bash-it completion symlink"
        fi
        yes | bash-it enable completion "$COMPLETION" > /dev/null && logg info "Enabled the bash-it $COMPLETION completion plugin" || logg error "Failed to install the $COMPLETION bash-it completion plugin"
      done

      ### Ensure plugins are enabled
      logg info 'Enabling bash-it plugins'
      # TODO: Move these plugins to the .chezmoidata.yaml
      for PLUGIN in base blesh browser cht-sh dirs gitstatus powerline sudo xterm; do
        if ls "$BASH_IT/enabled" | grep "$PLUGIN" > /dev/null; then
          rm -f "$BASH_IT/enabled/"*"$PLUGIN"* > /dev/null && logg info "Removed old $PLUGIN bash-it plugin symlink" || logg error "Failed to remove $PLUGIN bash-it plugin symlink"
        fi
        yes | bash-it enable plugin "$PLUGIN" > /dev/null && logg info "Enabled the bash-it $PLUGIN plugin" || logg error "Failed to install the $PLUGIN bash-it plugin"
      done
    else
      logg warn 'The path specified by BASH_IT does not exist yet'
    fi
  else
    if ! command -v powerline > /dev/null; then
      logg warn 'powerline is not available'
    else
      logg warn '~/.bashrc is missing'
    fi
  fi
}

# @description Performs various tasks related to integrating the Sweet icon theme that is part of our Betelgeuse theme
candyIconTweaks() {
  if [ "{{ .host.distro.family }}" = "linux" ]; then
    ### Merge latest Candy icons into the Betelgeuse icon theme
    if command -v rsync > /dev/null; then
      if [ -d "${XDG_DATA_HOME:-$HOME/.local/share}/candy-icons" ] && [ -d /usr/local/share/icons/Candy ]; then
        sudo rsync --chown=root:root --chmod=Du=rwx,Dg=rx,Do=rx,Fu=rw,Fg=r,Fo=r -artu --inplace --exclude .git/ "${XDG_DATA_HOME:-$HOME/.local/share}/candy-icons/" "/usr/local/share/icons/Candy/"
      else
        logg warn 'Skipping synchronization of Candy icons since either the target or destination folder is not present'
      fi
    else
      logg warn 'rsync is missing from the system!'
    fi

    ### Additional icons
    SOURCE_DIR="/usr/local/share/icons/Candy/apps/scalable"
    TARGET_DIR="/usr/local/share/icons/Candy/apps/scalable"
    if [ -d "$SOURCE_DIR" ] && [ -d "$TARGET_DIR" ]; then
      logg info 'Adding similar substitutes for some apps in the Candy icons theme'
      if [ -f "$SOURCE_DIR/youtube-dl-gui.svg" ] && [ ! -f "$TARGET_DIR/com.github.Johnn3y.Forklift.svg" ]; then
        sudo cp -f "$SOURCE_DIR/youtube-dl-gui.svg" "$TARGET_DIR/com.github.Johnn3y.Forklift.svg"
      fi
      if [ -f "$SOURCE_DIR/rdm.svg" ] && [ ! -f "$TARGET_DIR/app.resp.RESP.svg" ]; then
        sudo cp -f "$SOURCE_DIR/rdm.svg" "$TARGET_DIR/app.resp.RESP.svg"
      fi
      if [ -f "$SOURCE_DIR/preferences-system-power.svg" ] && [ ! -f "$TARGET_DIR/org.gnome.PowerStats.svg" ]; then
        sudo cp -f "$SOURCE_DIR/preferences-system-power.svg" "$TARGET_DIR/org.gnome.PowerStats.svg"
      fi
      if [ -f "$SOURCE_DIR/software-store.svg" ] && [ ! -f "$TARGET_DIR/software-properties-gtk.svg" ]; then
        sudo cp -f "$SOURCE_DIR/software-store.svg" "$TARGET_DIR/software-properties-gtk.svg"
      fi
      if [ -f "$SOURCE_DIR/preferences-desktop-remote-desktop.svg" ] && [ ! -f "$TARGET_DIR/org.gnome.Connections.svg" ]; then
        sudo cp -f "$SOURCE_DIR/preferences-desktop-remote-desktop.svg" "$TARGET_DIR/org.gnome.Connections.svg"
      fi
      if [ -f "$SOURCE_DIR/com.github.wwmm.pulseeffects.svg" ] && [ ! -f "$TARGET_DIR/com.mattjakeman.ExtensionManager.svg" ]; then
        sudo cp -f "$SOURCE_DIR/com.github.wwmm.pulseeffects.svg" "$TARGET_DIR/com.mattjakeman.ExtensionManager.svg"
      fi
    fi

    ### Icons added to fork (https://github.com/ProfessorManhattan/candy-icons)
    # These commented out icons already had good matches in the Sweet theme so a fork was created
    # and a pull request was open for them.
    # sudo cp -f "$SOURCE_DIR/gitkraken.svg" "$TARGET_DIR/com.axosoft.GitKraken.svg"
    # sudo cp -f "$SOURCE_DIR/github-desktop.svg" "$TARGET_DIR/io.github.shiftey.Desktop"
    # sudo cp -f "$SOURCE_DIR/inkscape.svg" "$TARGET_DIR/inkscape_inkscape.desktop"
    # sudo cp -f "$SOURCE_DIR/cutter.svg" "$TARGET_DIR/re.rizin.cutter.svg"
    # sudo cp -f "$SOURCE_DIR/arduino.svg" "$TARGET_DIR/cc.arduino.IDE2.svg"    
    # sudo cp -f "$SOURCE_DIR/intellij.svg" "$TARGET_DIR/intellij-idea-community_intellij-idea-community.svg"
    # sudo cp -f "$SOURCE_DIR/google-chrome.svg" "$TARGET_DIR/com.google.Chrome.svg"
    # sudo cp -f "$SOURCE_DIR/firefox.svg" "$TARGET_DIR/org.mozilla.firefox.svg"
    # sudo cp -f "$SOURCE_DIR/microsoft-edge.svg" "$TARGET_DIR/com.microsoft.Edge.svg"
    # sudo cp -f "$SOURCE_DIR/thunderbird.svg" "$TARGET_DIR/org.mozilla.Thunderbird.svg"
    # sudo cp -f "$SOURCE_DIR/postman.svg" "$TARGET_DIR/com.getpostman.Postman.svg"
    # sudo cp -f "$SOURCE_DIR/plexhometheater.svg" "$TARGET_DIR/tv.plex.PlexDesktop.svg"
    # sudo cp -f "$SOURCE_DIR/seafile.svg" "$TARGET_DIR/com.client.Seafile.svg"
    # sudo cp -f "$SOURCE_DIR/com.github.gi_lom.dialect.svg" "$TARGET_DIR/app.drey.Dialect.svg"
    sudo cp -f "$SOURCE_DIR/teamviewer.svg" "$TARGET_DIR/com.teamviewer.TeamViewer.svg"
    sudo cp -f "$SOURCE_DIR/terminator.svg" "$TARGET_DIR/tabby.svg"

    ### Missing icons
    # The following applications are missing icons after using the "Full" installer. The application name
    # is listed. To the right of each hyphen is the name of the `.desktop` file.
    # Webkit Font Generator - 
    # Lepton - lepton_lepton
    # scrcpygui
    # scrcpy - scrcpy_scrcpy
    # Shotcut - org.shotcut.Shotcut
    # Kooha - io.github.seadve.Kooha
    # Lens - kontena-lens_kontena-lens
    # Proton Mail Bridge - ch.protonmail.protonmail-bridge
    # Proton Import-Export app - ch.protonmail.protonmail-import-export-app
    # MQTTX - com.emqx.MQTTX
    # Mockoon - mockoon_mockoon
    # PowerShell - powershell_powershell
    # GNOME Network Displays - org.gnome.NetworkDisplays
    # Cockpit Client - org.cockpit_project.CockpitClient
    # Yubico Authenticator - com.yubico.yubioath
    # OnlyKey App - onlykey-app_onlykey-app
    # Element - im.riot.Riot
    # Jitsi Meet - org.jitsi.jitsi-meet
    # Keybase
    # Nuclear - org.js.nuclear.Nuclear
    # Motrix - net.agalwood.Motrix
    # Raspberry Pi Imager - org.raspberrypi.rpi-imager
    # Junction - re.sonny.Junction
    # GNOME Extension Manager - com.mattjakeman.ExtensionManager
    # Startup Applications
    # Multipass - multipass_gui
    # Portmaster - portmaster, portmaster_notifier
    # GNOME Connections - org.gnome.Connections

    ### Copy Snap desktop links to ~/.local/share/applications to apply custom icons
    find /var/lib/snapd/desktop/applications -mindepth 1 -maxdepth 1 -name "*.desktop" | while read DESKTOP_FILE; do
      DESKTOP_FILE_BASE="$(basename "$DESKTOP_FILE" | sed 's/.desktop$//')"
      SNAP_ICON_BASE="$(echo "$DESKTOP_FILE_BASE" | sed 's/^[^_]*_//')"
      if [ -f "/usr/local/share/icons/Candy/apps/scalable/${DESKTOP_FILE_BASE}.svg" ] || [ -f "/usr/local/share/icons/Candy/apps/scalable/${SNAP_ICON_BASE}.svg" ]; then
        logg info "Found matching Candy icon theme icon for $DESKTOP_FILE"
        if [ ! -f "${XDG_DATA_HOME:-$HOME/.local/share}/applications/${DESKTOP_FILE_BASE}.desktop" ]; then
          cp "$DESKTOP_FILE" "${XDG_DATA_HOME:-$HOME/.local/share}/applications"
          logg info "Copied the .desktop shortcut to ${XDG_DATA_HOME:-$HOME/.local/share}/applications"
          if [ -f "/usr/local/share/icons/Candy/apps/scalable/${SNAP_ICON_BASE}.svg" ]; then
            SNAP_ICON="${SNAP_ICON_BASE}"
          else
            SNAP_ICON="${DESKTOP_FILE_BASE}"
          fi
          logg info 'Setting the .desktop shortcut Icon value equal to '"$SNAP_ICON"''
          sed -i 's/^Icon=.*$/Icon='"$SNAP_ICON"'/' "${XDG_DATA_HOME:-$HOME/.local/share}/applications/${DESKTOP_FILE_BASE}.desktop"
        else
          logg info "${XDG_DATA_HOME:-$HOME/.local/share}/applications/${DESKTOP_FILE_BASE}.desktop already exists!"
        fi
      fi
    done
  fi
}

# @description
#     This script ensures VNC is setup and enabled. It will run on macOS always since macOS includes
#     a VNC server baked into its system. On Linux, it will check for the presence of the `tightvncserver`
#     package before configuring and enabling VNC.
#
#     The script will set the VNC password using the `VNC_PASSWORD` environment variable or the encrypted
#     equivalent stored in `home/.chezmoitemplates/secrets`. If neither are provided, then the default
#     password will be equal to `vncpass` since the password must be between 6-8 characters long.
#
#     Additionally, the `VNC_READ_PASSWORD` can be defined to allow read-only VNC sessions. The default password
#     for a read-only session is `readonly`.
configureVNC() {
  if [ -d /Applications ] && [ -d /System ]; then
    ### macOS
    # Source: https://apple.stackexchange.com/questions/30238/how-to-enable-os-x-screen-sharing-vnc-through-ssh
    # To disable, run: sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -deactivate -configure -access -off
    # Only enable when computer is not a corporate / work computer
    logg info 'Enabling VNC using the VNC_PASSWORD variable which is vncpass when nothing is specified'
    sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -allowAccessFor -specifiedUsers -clientopts -setreqperm -reqperm yes -setvnclegacy -vnclegacy yes -setvncpw -vncpw "{{- if and (stat (joinPath .host.home ".config" "age" "chezmoi.txt")) (stat (joinPath .chezmoi.sourceDir ".chezmoitemplates" "secrets" "VNC_PASSWORD")) }}{{ includeTemplate "secrets/VNC_PASSWORD" | decrypt | trim }}{{ else }}{{ default "vncpass" (env "VNC_PASSWORD") }}{{ end }}" -restart -agent -privs -all -users "$USER" && logg info 'Finished running the macOS Remote Management kickstart executable'
  else
    ### Linux
    ### VNC set-up / configuration
    # KasmVNC / TigerVNC (or alternative VNC program) is installed
    if command -v kasmvncpasswd > /dev/null; then
      logg info 'Copying VNC configuration files from ~/.config/vnc/etc/kasmvnc/ to /etc/'
      sudo cp -Rf "${XDG_CONFIG_HOME:-$HOME/.config}/vnc/etc/kasmvnc/" /etc/
      logg info 'Adding VNC full-control password to ~/.config/vnc/kasmpasswd'
      echo -e "{{- if and (stat (joinPath .host.home ".config" "age" "chezmoi.txt")) (stat (joinPath .chezmoi.sourceDir ".chezmoitemplates" "secrets" "VNC_PASSWORD")) }}{{ includeTemplate "secrets/VNC_PASSWORD" | decrypt | trim }}{{ else }}{{ default "vncpass" (env "VNC_PASSWORD") }}{{ end }}\n{{- if and (stat (joinPath .host.home ".config" "age" "chezmoi.txt")) (stat (joinPath .chezmoi.sourceDir ".chezmoitemplates" "secrets" "VNC_PASSWORD")) }}{{ includeTemplate "secrets/VNC_PASSWORD" | decrypt | trim }}{{ else }}{{ default "vncpass" (env "VNC_PASSWORD") }}{{ end }}" | kasmvncpasswd -u {{ .user.name }} -rwo
      logg info 'Adding VNC read-only password to ~/.config/vnc/kasmpasswd for user readonly'
      echo -e "{{- if and (stat (joinPath .host.home ".config" "age" "chezmoi.txt")) (stat (joinPath .chezmoi.sourceDir ".chezmoitemplates" "secrets" "VNC_READ_PASSWORD")) }}{{ includeTemplate "secrets/VNC_READ_PASSWORD" | decrypt | trim }}{{ else }}{{ default "readonly" (env "VNC_READ_PASSWORD") }}{{ end }}\n{{- if and (stat (joinPath .host.home ".config" "age" "chezmoi.txt")) (stat (joinPath .chezmoi.sourceDir ".chezmoitemplates" "secrets" "VNC_READ_PASSWORD")) }}{{ includeTemplate "secrets/VNC_READ_PASSWORD" | decrypt | trim }}{{ else }}{{ default "readonly" (env "VNC_READ_PASSWORD") }}{{ end }}" | kasmvncpasswd -u guest -r
      logg info 'Reloading the systemctl configuration files since a new one for VNC may have been added'
      sudo systemctl daemon-reload
      logg info 'Enabling / starting the VNC service for the current user / display 1'
      sudo systemctl start vncserver@1
      sudo systemctl enable vncserver@1
      if command -v update-alternatives > /dev/null; then
        update-alternatives --set vncserver "$(which kasmvncserver)"
        update-alternatives --set vncpasswd "$(which kasmvncpasswd)"
        update-alternatives --set Xvnc "$(which Xkasmvnc)"
        update-alternatives --set vncconfig "$(which kasmvncconfig)"
      fi
    elif command -v tigervncpasswd > /dev/null; then
      if [ ! -d "${XDG_CONFIG_HOME:-$HOME/.config}/vnc" ]; then
        mkdir -p "${XDG_CONFIG_HOME:-$HOME/.config}/vnc"
      fi
      logg info 'Copying VNC configuration files from ~/.config/vnc/etc/tigervnc/ to /etc/'
      sudo cp -Rf "${XDG_CONFIG_HOME:-$HOME/.config}/vnc/etc/tigervnc/" /etc/
      logg info 'Adding VNC full-control password to ~/.config/vnc/passwd'
      echo -n "{{- if and (stat (joinPath .host.home ".config" "age" "chezmoi.txt")) (stat (joinPath .chezmoi.sourceDir ".chezmoitemplates" "secrets" "VNC_PASSWORD")) }}{{ includeTemplate "secrets/VNC_PASSWORD" | decrypt | trim }}{{ else }}{{ default "vncpass" (env "VNC_PASSWORD") }}{{ end }}" | tigervncpasswd -f > "${XDG_CONFIG_HOME:-$HOME/.config}/vnc/passwd"
      logg info 'Adding VNC read-only password to ~/.config/vnc/passwd'
      echo -n "{{- if and (stat (joinPath .host.home ".config" "age" "chezmoi.txt")) (stat (joinPath .chezmoi.sourceDir ".chezmoitemplates" "secrets" "VNC_READ_PASSWORD")) }}{{ includeTemplate "secrets/VNC_READ_PASSWORD" | decrypt | trim }}{{ else }}{{ default "readonly" (env "VNC_READ_PASSWORD") }}{{ end }}" | tigervncpasswd -f >> "${XDG_CONFIG_HOME:-$HOME/.config}/vnc/passwd"
      logg info 'Reloading the systemctl configuration files since a new one for VNC may have been added'
      sudo systemctl daemon-reload
      logg info 'Enabling / starting the VNC service for the current user / display 1'
      sudo systemctl start vncserver@1
      sudo systemctl enable vncserver@1
    else
      logg info 'Skipping VNC setup since the tightvncserver package is not present on the system'
    fi
  fi
}

# @description Move ~/.gnome/apps/* to ~/.local/share/applications
moveGnomeAppsToShare() {
  if [ -d "$HOME/.gnome/apps" ]; then
    if [ ! -d "${XDG_DATA_HOME:-$HOME/.local/share}/applications" ]; then
      mkdir -p "${XDG_DATA_HOME:-$HOME/.local/share}/applications"
    fi
    find "$HOME/.gnome/apps" -mindepth 1 -maxdepth 1 -type f | while read DESKTOP_FILE; do
      logg info "Moving $DESKTOP_FILE to ${XDG_DATA_HOME:-$HOME/.local/share}/applications/$(basename "$DESKTOP_FILE")"
      mv "$DESKTOP_FILE" "${XDG_DATA_HOME:-$HOME/.local/share}/applications/$(basename "$DESKTOP_FILE")"
      chmod 755 "${XDG_DATA_HOME:-$HOME/.local/share}/applications/$(basename "$DESKTOP_FILE")"
    done
    logg info 'Removing ~/.gnome/apps'
    rm -rf "$HOME/.gnome/apps"
  fi
}

# @description
#     This script ensures that the first time you open a ZSH terminal session everything is loaded as fast as possible.
#     It does this by invoking ZSH in the background during the provisioning process so that "first-run" tasks such
#     as cache-building are handled ahead of time.
preloadZsh() {
  ### Initialize ZSH so plugin bootstrap process is done ahead of time
  if command -v zsh > /dev/null; then
    logg info 'Bootstrapping ZSH by running exec zsh'
    exec zsh &
    logg info 'Waiting for exec zsh to finish'
    wait
  fi
}

# @description
#     This script loops through the `.removeLinuxShortcuts` value in `home/.chezmoidata.yaml` and removes
#     desktop shortcuts that have been deemed to be unnecessary or obtrusive.
removeShortcutsLinux() {
  if [ "{{ .host.distro.family }}" = "linux" ]; then
    logg info 'Processing remove shortcuts step for Linux machines'

    ### Remove unnecessary desktop shortcuts
    for DESKTOP_ICON in {{ join " " .removeLinuxShortcuts }}; do
      for SHORTCUT_FOLDER in {{ .host.home }}/.local/share/applications {{ .host.home }}/.local/share/applications/wine/Programs; do
        if [ -f "$SHORTCUT_FOLDER/$DESKTOP_ICON" ]; then
          rm -f "$SHORTCUT_FOLDER/$DESKTOP_ICON"
        fi
      done
      for SHORTCUT_FOLDER in /usr/share/applications /usr/local/share/applications /var/lib/snapd/desktop/applications; do
        if [ -f "$SHORTCUT_FOLDER/$DESKTOP_ICON" ]; then
          sudo rm -f "$SHORTCUT_FOLDER/$DESKTOP_ICON"
        fi
      done
    done
  fi
}

# @description Remove Ubuntu logo branding from GDM lock screen
removeUbuntuLogoBranding() {
  if [ '{{ .whiteLabel }}' == 'true' ] && [ -f /usr/share/plymouth/ubuntu-logo.png ]; then
    logg info 'Renaming /usr/share/plymouth/ubuntu-logo.png to /usr/share/plymouth/ubuntu-logo.png.bak since the whiteLabel setting is true'
    sudo mv /usr/share/plymouth/ubuntu-logo.png /usr/share/plymouth/ubuntu-logo.png.bak
  fi
}

# @description
#     This script sets the default browser to the value stored in [`.chezmoi.yaml.tmpl`](https://github.com/megabyte-labs/install.doctor/tree/master/home/.chezmoi.yaml.tmpl)
#     under the `user` section.
#
#     * On macOS, it uses the `defaultbrowser` Homebrew package to update the default browser.
#     * On Linux, it uses a combination of `xdg-mime` and `xdg-settings` options to update the default browser.
#
#     The default browser for terminal applications is stored as the `BROWSER` value which is
#     defined at the end of the [`exports.sh.tmpl`](https://github.com/megabyte-labs/install.doctor/tree/master/home/dot_config/shell/exports.sh.tmpl)
#     file. This value is also populated from the `.chezmoi.yaml.tmpl` value.
setDefaultBrowser() {
  if [ -d /Applications ] && [ -d /System ]; then
    if ! command -v defaultbrowser > /dev/null; then
      logg info 'Installing defaultbrowser via Homebrew which is the preferred way of configuring the default browser'
      brew install --quiet defaultbrowser
    fi
    logg info "Setting default browser to {{ .user.defaultBrowserDarwin }}"
    osascript "$HOME/Library/Scripts/default-browser.scpt" "{{ .user.defaultBrowserDarwin }}" || EXIT_CODE=$?
    if [ -n "$EXIT_CODE" ]; then
      logg error 'Failed to change default browser'
      unset EXIT_CODE
    fi
  else
    logg info 'Setting default browser for text/html to {{ .user.defaultBrowser }}'
    xdg-mime default {{ .user.defaultBrowser }}.desktop text/html
    logg info 'Setting default browser for x-scheme-handler/http to {{ .user.defaultBrowser }}'
    xdg-mime default {{ .user.defaultBrowser }}.desktop x-scheme-handler/http
    logg info 'Setting default browser for x-scheme-handler/https to {{ .user.defaultBrowser }}'
    xdg-mime default {{ .user.defaultBrowser }}.desktop x-scheme-handler/https
    logg info 'Setting default browser for x-scheme-handler/about to {{ .user.defaultBrowser }}'
    xdg-mime default {{ .user.defaultBrowser }}.desktop x-scheme-handler/about
    logg info 'Setting default browser with xdg-settings to {{ .user.defaultBrowser }}'
    xdg-settings set default-web-browser {{ .user.defaultBrowser }}.desktop
  fi
}

# @description Fix for Ubuntu default extension conflicting with dash-to-dock
ubuntuDashToDockFix() {
  if command -v dconf > /dev/null; then
    if dconf read /org/gnome/shell/enabled-extensions | grep dash-to-dock > /dev/null; then
      if [ -d '/usr/share/gnome-shell/extensions/ubuntu-dock@ubuntu.com' ]; then
        if [ ! -d /usr/share/gnome-shell/extensions/disabled ]; then
          sudo mkdir /usr/share/gnome-shell/extensions/disabled
          logg info 'Created /usr/share/gnome-shell/extensions/disabled for GNOME extensions that have issues'
        fi
        sudo mv '/usr/share/gnome-shell/extensions/ubuntu-dock@ubuntu.com' '/usr/share/gnome-shell/extensions/disabled/ubuntu-dock@ubuntu.com'
        logg info 'Moved ubuntu-dock@ubuntu.com to the disabled extension folder'
      fi
    fi
  fi
}

if [ -n "$DEBUG" ] || [ -n "$DEBUG_MODE" ]; then
  logg info 'The DEBUG or DEBUG_MODE environment variable is set so the post-install tasks will be run synchronously'
  bashItPlugins
  candyIconTweaks
  configureVNC
  moveGnomeAppsToShare
  preloadZsh
  removeShortcutsLinux
  removeUbuntuLogoBranding
  setDefaultBrowser
  ubuntuDashToDockFix
else
  bashItPlugins &
  candyIconTweaks &
  configureVNC &
  moveGnomeAppsToShare &
  preloadZsh &
  removeShortcutsLinux &
  removeUbuntuLogoBranding &
  setDefaultBrowser &
  ubuntuDashToDockFix &
  wait
fi

logg success 'Finished running the post-install tasks'