#!/bin/bash

## Copyright (C) 2012 - 2020 ENCRYPTED SUPPORT LP <adrelanos@riseup.net>
## See the file COPYING for copying conditions.

## Gets started by /etc/profile.d/30_setup.sh.

## Using this script and not directly using /etc/profile.d/30_setup.sh,
## because /etc/profile.d/30_setup.sh gets `source`d, not executed, by
## /etc/profile. We would have to use "return". "exit" would not be
## available (without stopping /etc/profile to source the rest of the
## /etc/profile.d folder). Using this script has also the advantage,
## that /bin/bash's features can be used.

#set -x
set -o errtrace
set -o pipefail

error_handler_setup() {
   echo "[${red}${bold}ERROR${reset}] [whonixsetup] \
ret: $? | BASH_COMMAND: $BASH_COMMAND | Please report this bug!"
}

trap "error_handler_setup" ERR

sigterm_setup() {
   #echo "[${green}INFO${reset}] [whonixsetup] SIGTERM received!"
   true "INFO: [whonixsetup] SIGTERM received!"
}

trap "sigterm_setup" SIGTERM
trap "sigterm_setup" SIGINT

colors() {
   if [ "$TERM" = "" ]; then
      return 0
   fi

## Thanks to:
## http://mywiki.wooledge.org/BashFAQ/037
## Variables for terminal requests.
[[ -t 2 ]] && {
    alt=$(      tput smcup  || tput ti      ) # Start alt display
    ealt=$(     tput rmcup  || tput te      ) # End   alt display
    hide=$(     tput civis  || tput vi      ) # Hide cursor
    show=$(     tput cnorm  || tput ve      ) # Show cursor
    save=$(     tput sc                     ) # Save cursor
    load=$(     tput rc                     ) # Load cursor
    bold=$(     tput bold   || tput md      ) # Start bold
    stout=$(    tput smso   || tput so      ) # Start stand-out
    estout=$(   tput rmso   || tput se      ) # End stand-out
    under=$(    tput smul   || tput us      ) # Start underline
    eunder=$(   tput rmul   || tput ue      ) # End   underline
    reset=$(    tput sgr0   || tput me      ) # Reset cursor
    blink=$(    tput blink  || tput mb      ) # Start blinking
    italic=$(   tput sitm   || tput ZH      ) # Start italic
    eitalic=$(  tput ritm   || tput ZR      ) # End   italic
[[ $TERM != *-m ]] && {
    red=$(      tput setaf 1|| tput AF 1    )
    green=$(    tput setaf 2|| tput AF 2    )
    yellow=$(   tput setaf 3|| tput AF 3    )
    blue=$(     tput setaf 4|| tput AF 4    )
    magenta=$(  tput setaf 5|| tput AF 5    )
    cyan=$(     tput setaf 6|| tput AF 6    )
}
    white=$(    tput setaf 7|| tput AF 7    )
    default=$(  tput op                     )
    eed=$(      tput ed     || tput cd      )   # Erase to end of display
    eel=$(      tput el     || tput ce      )   # Erase to end of line
    ebl=$(      tput el1    || tput cb      )   # Erase to beginning of line
    ewl=$eel$ebl                                # Erase whole line
    draw=$(     tput -S <<< '   enacs
                                smacs
                                acsc
                                rmacs' || { \
                tput eA; tput as;
                tput ac; tput ae;         } )   # Drawing characters
    back=$'\b'
} 2>/dev/null ||:
}

start_whonixsetup_cli_and_exit() {
   ## This has a sudoers exception in /etc/sudoers.d/whonixsetup.
   sudo --non-interactive whonixsetup
   exit 0
}

maybe_start_setup() {
   if [ -e "/run/rads/start_x.status" ]; then
      true "[${green}INFO${reset}] [whonixsetup] Not starting whonixsetup in \
terminal, because rads reports, that X is going to be started. (Autostarting \
whonix-setup-wizard in X is handled by \
/etc/xdg/autostart/whonixsetup.desktop.)"
      exit 0
   elif [ -e "/run/rads/no_start_x.status" ]; then
      true "[${green}INFO${reset}] [whonixsetup] rads appears to be \
installed. /run/rads/no_start_x.status exists."
   else
      true "[${green}INFO${reset}] [whonixsetup] rads appears not to be \
in use."
   fi

   if [ -f "/usr/share/whonix-setup-wizard/status-files/whonixsetup.skip" ]; then
      true "[${green}INFO${reset}] [whonixsetup] skip file \
/usr/share/whonix-setup-wizard/status-files/whonixsetup.skip exists. Exiting."
      exit 0
   fi

   if [ -e "/usr/share/anon-gw-base-files/gateway" ]; then
      ## Checking if Tor has been enabled.
      ## And if Tor has not been enabled, auto start whonixsetup (cli).
      ## This function only gets called, if we are not booting into a graphical desktop environment.
      ## Eventually auto starting whonix-setup-wizard (gui) in a graphical desktop environment is
      ## implemented through /etc/xdg/autostart/whonix-setup-wizard.desktop.

      source /usr/lib/helper-scripts/tor_enabled_check

      ## disable trap /usr/lib/helper-scripts/tor_enabled_check may have enabled
      trap "error_handler_setup" ERR

      ## Check if Tor is enabled.
      ## returns: TOR_ENABLED
      check_tor_enabled_do

      ## disable trap of check_tor_enabled_do
      trap "error_handler_setup" ERR

      if [ "$TOR_ENABLED" = "0" ]; then
         ## Look and feel.
         sleep 5 &
         wait "$!" || true

         echo "[${green}INFO${reset}] [whonixsetup] Tor has not been enabled yet. Starting whonixsetup..."

         ## Sleep just for the look and feel, so the following message comes after, so the previous
         ## message can be read.
         sleep 5 &
         wait "$!" || true

         start_whonixsetup_cli_and_exit
      fi
   fi

   ## Now, the script is either:
   ## - Running on Whonix-Gateway, where Tor has been previously already
   ##   enabled (custom builds or derivatives).
   ## - Running on Whonix-Workstation.

   if [ -f "/var/cache/whonix-setup-wizard/status-files/whonixsetup.done" ]; then
      true "[${green}INFO${reset}] [whonixsetup] done file \
/var/cache/whonix-setup-wizard/status-files/whonixsetup.done exists. Exiting."
      exit 0
   fi
   ## Legacy up to build version 9.x.
   if [ -f "/var/lib/whonix/do_once/whonixsetup.done" ]; then
      true "[${green}INFO${reset}] [whonixsetup] legacy done file \
/var/lib/whonix/do_once/whonixsetup.done exists. Exiting."
      exit 0
   fi

   sleep 5 &
   wait "$!" || true

   echo "[${green}INFO${reset}] [whonixsetup] Starting whonixsetup..."

   sleep 5 &
   wait "$!" || true

   start_whonixsetup_cli_and_exit
}

colors
maybe_start_setup
