#!/bin/bash

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

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

source /usr/libexec/helper-scripts/has.sh
source /usr/libexec/helper-scripts/log_run_die.sh
source /usr/libexec/helper-scripts/package_installed_check.sh
source /usr/libexec/helper-scripts/check_runtime.bsh

if was_sourced "${BASH_SOURCE[0]}"; then
  die 1 "Do not source this script!"
fi

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

build_whonix_starter() {
  local dep_command_list dep_command_pkg_list dep_pkg_list idx dep_pkg \
    whonix_starter_version

  dep_command_list=( 'makensis' 'lazbuild' 'xmllint' )
  dep_command_pkg_list=( 'nsis' 'lazarus-ide' 'libxml2-utils' )
  dep_pkg_list=(
    'fp-units-win-base'
    'fp-units-win-rtl'
    'fp-units-win-fcl'
    'fp-units-win-misc'
  )

  for idx in "${!dep_command_list[@]}"; do
    if ! has "${dep_command_list[idx]}"; then
      die 1 "Cannot find command '${dep_command_list[idx]}'! Is the '${dep_command_pkg_list[idx]}' package installed?"
    fi
  done
  for dep_pkg in "${dep_pkg_list[@]}"; do
    if ! pkg_installed "${dep_pkg}"; then
      die 1 "Package '${dep_pkg}' is not installed!"
    fi
  done

  log notice 'Getting Whonix-Starter version...'
  log notice "Command executing: $ xmllint --xpath string(//VersionInfo/StringTable/@ProductVersion) ${MYDIR}/WhonixStarter.lpi"
  whonix_starter_version="$(xmllint --xpath 'string(//VersionInfo/StringTable/@ProductVersion)' "${MYDIR}/WhonixStarter.lpi")"
  log notice "Detected Whonix-Starter version '${whonix_starter_version}'."

  log notice 'Building Whonix-Starter for Windows...'
  log_run notice lazbuild \
    --lazarusdir=/usr/lib/lazarus/4.0 \
    -B \
    "${MYDIR}/WhonixStarter.lpi" \
    --cpu=x86_64 \
    --os=win64
  log notice 'Whonix-Starter for Windows build.'

  log notice 'Building NSIS installer for Whonix-Starter...'
  log_run notice makensis \
    -DVersion="${whonix_starter_version}" \
    -V4 \
    -WX \
    "${MYDIR}/WhonixStarter.nsi"
  log notice 'NSIS installer for Whonix-Starter built.'
}

build_whonix_starter
