#!/bin/bash

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

set -x
set -e

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

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

cd "$MYDIR"
cd ..
cd help-steps

source pre
source colors
source variables

analyze_target() {
   local target image_to_analyze
   target="$1"
   image_to_analyze="$2"

   local topcomment
   topcomment="\
INFO: This is an auto-generated file.
See https://www.whonix.org/wiki/Verifiable_Builds
and https://www.whonix.org/wiki/Trust
to learn what this is about.
dist_build_current_git_head: $dist_build_current_git_head
dist_build_new_changelog_version: $dist_build_new_changelog_version
dist_build_version: $dist_build_version
dist_build_install_to_root: $dist_build_install_to_root"

   local endcomment
   endcomment="INFO: End."

   local errorcomment
   errorcomment="ERROR: Unfinished report! Error detected!"

   true "${cyan}INFO: analyzing $target... ${reset}"

   report_file="$binary_build_folder_dist/$VMNAME-$dist_build_version.$target.report"
   report_tempfolder="$binary_build_folder_dist/$VMNAME-${dist_build_version}_report_${target}_tempfolder"

   "$dist_source_help_steps_folder/analyze_image" \
      $minimal_report_maybe \
      --topcomment "$topcomment" \
      --endcomment "$endcomment" \
      --errorcomment "$errorcomment" \
      --report "$report_file" \
      --tempfolder "$report_tempfolder" \
      "--$target" "$image_to_analyze"

   true "${cyan}INFO: Done, analyzed $target. ${reset}"
}

main() {
   if [ "$build_dry_run" = "true" ]; then
      true "${bold}${cyan}INFO: dry-run, skipping $BASH_SOURCE. ${reset}"
      return 0
   fi

   if [ "$dist_build_fast2" = "1" ]; then
      echo "${bold}${cyan}INFO: run with '--fast 2' switch, skipping $BASH_SOURCE. ${reset}"
      return 0
   fi

   if [ ! "$dist_build_script_create_report" = "true" ]; then
      true "${bold}${cyan}INFO: run without --report true, skipping, ok. ${reset}"
      return 0
   fi

   local report_file report_tempfolder

   if [ "$dist_build_install_to_root" = "true" ]; then
      analyze_target "root" "/"
   fi

   if [ "$dist_build_raw" = "true" ]; then
      analyze_target "raw" "$binary_image_raw_file"
   fi

   if [ "$dist_build_virtualbox" = "true" ]; then
      analyze_target "ova" "$binary_image_ova_file"
   fi

   if [ "$dist_build_qcow2" = "true" ]; then
      analyze_target "qcow2" "$binary_image_qcow2_file"
   fi

   if [ "$dist_build_iso" = "true" ]; then
      error "Not implemented!"
   fi
}

main "$@"
