#!/usr/bin/python3 -u

## Copyright (C) 2014 troubadour <trobador@riseup.net>
## Copyright (C) 2014 - 2024 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## Decides to autostart setup-wizard-dist or not.
## - Do not start when a done or skip file exists.
## - Do not start in Kicksecure-Qubes.
## - Do not start in Qubes-Whonix-Workstation.
## - Do not start in a Qubes Template.
## - Start in Kicksecure (non-Qubes).
## - Start in Qubes-Whonix-Gateway.
## - Start in Non-Qubes-Whonix-Gateway.
## - Start in Non-Qubes-Whonix-Workstation.

import sys
import os
import time
from subprocess import call

if (os.path.exists('/var/lib/whonix/do_once/whonixsetup.done') or
   os.path.exists('/var/cache/whonix-setup-wizard/status-files/whonixsetup.done') or
   os.path.exists('/usr/share/whonix-setup-wizard/status-files/whonixsetup.skip') or
   os.path.exists('/var/cache/setup-dist/status-files/setup-dist.done') or
   os.path.exists('/usr/share/setup-dist/status-files/setup-dist.skip')
):
   print('/usr/libexec/setup-wizard-dist/setup-dist_check_for_start: setup-dist done file exists. Exiting.')
   sys.exit()

if os.path.exists('/run/qubes/this-is-templatevm'):
   print('/usr/libexec/setup-wizard-dist/setup-dist_check_for_start: File /run/qubes/this-is-templatevm exists. Exiting.')
   sys.exit()

if os.path.exists('/usr/share/qubes/marker-vm'):
   ## Qubes detected.
   if os.path.exists('/usr/share/anon-gw-base-files/gateway'):
      ## Display alert that 'whonix-tor-disable' service flag is set and it will need to
      ## to manually unset if user wants to be able to boot with Tor enabled.
      ## TODO: Don't depend on qubes-whonix package / 'alert' script by qubes-whonix package.
      ##       Abolish 'alert' script. Merge into systemcheck and/or anon-connection-wizard.
      ##       https://phabricator.whonix.org/T656
      if os.path.exists('/run/qubes-service/whonix-tor-disable'):
         command = '/usr/lib/qubes-whonix/alert tor-disabled /usr/lib/qubes-whonix/messages.yaml'
         call(command, shell = True)
         sys.exit()
   else:
      print('/usr/libexec/setup-wizard-dist/setup-dist_check_for_start: Qubes-Whonix-Gateway not detected. Therefore do not start setup-wizard-dist by default. Exiting.')
      sys.exit()

if os.path.exists('/usr/share/anon-gw-base-files/gateway'):
   print('/usr/libexec/setup-wizard-dist/setup-dist_check_for_start: Whonix-Gateway detected.')
elif os.path.exists('/usr/share/anon-ws-base-files/workstation'):
   print('/usr/libexec/setup-wizard-dist/setup-dist_check_for_start: Whonix-Workstation detected.')
else:
   print('/usr/libexec/setup-wizard-dist/setup-dist_check_for_start: Neither Whonix-Gateway nor Whonix-Workstation detected. Exiting.')
   sys.exit()

print('/usr/libexec/setup-wizard-dist/setup-dist_check_for_start: executing /usr/libexec/setup-wizard-dist/setup-wizard-dist')
command = '/usr/libexec/setup-wizard-dist/setup-wizard-dist'
call(command, shell=True)
