#!/bin/bash

## Copyright (C) 2012 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## example usage:
## Requires local repository already created.
## sudo dm-install-from-local-repository --target root --flavor whonix-gateway --build

set -x
set -e

true "INFO: Currently running script: $BASH_SOURCE $@"

MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$MYDIR"

source ~/derivative-maker/help-steps/pre
source ~/derivative-maker/help-steps/colors
source ~/derivative-maker/help-steps/variables

main() {
   trap "exception_handler_unchroot_unmount" ERR INT TERM

   ## Move existing /etc/apt/sources.list out of the way.
   if ! test -e /etc/apt/sources.list.backup ; then
      if test -e /etc/apt/sources.list ; then
         mv /etc/apt/sources.list /etc/apt/sources.list.backup || true
      fi
   fi

   ## This file doesn't include Whonix's APT repository.
   cp "$source_code_folder_dist/packages/anon-apt-sources-list/etc/apt/sources.list.d/debian.list" "$CHROOT_FOLDER/etc/apt/sources.list.d/"

   "$dist_source_help_steps_folder/create-local-temp-apt-repo" "$@"

   ## Reading local repository containing Whonix's packages.
   $CHROOT apt-get ${APTGETOPT[@]} $apt_sourcelist_empty $apt_sourceparts -o APT::Get::List-Cleanup="0" update

   if [ "$pkg" = "" ]; then
      if [ "$dist_build_flavor" = "whonix-gateway-kde" ]; then
         if [ "$dist_build_qubes" = "true" ]; then
            pkg="qubes-whonix-gateway-kde"
         else
            pkg="non-qubes-whonix-gateway"
         fi
      elif [ "$dist_build_flavor" = "whonix-workstation-kde" ]; then
         if [ "$dist_build_qubes" = "true" ]; then
            pkg="qubes-whonix-workstation"
         else
            pkg="non-qubes-whonix-workstation-kde"
         fi
      else
         local MSG="${bold}${red}$BASH_SOURCE ERROR: VMNAME is neither Whonix-Gateway nor Whonix-Workstation. Please report this bug! ${reset}"
         error "$MSG"
      fi
   fi

   $CHROOT apt-get ${APTGETOPT[@]} $apt_sourcelist_empty $apt_sourceparts --yes install $pkg

   #$CHROOT apt-get ${APTGETOPT[@]} $apt_sourcelist_empty $apt_sourceparts -f install

   "$dist_source_help_steps_folder/remove-local-temp-apt-repo" "$@"

   ## Forget about local repository containing Whonix's packages.
   $CHROOT apt-get --no-download --list-cleanup update
}

main "$@"
