#!/bin/bash

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

## NOTE: No longer in use.

set -x
set -e

FPC_VERSION=3.2.2
FPC_COMMIT_FOR_VERSION=0d122c49534b480be9284c21bd60b53d99904346 # 3.2.2

CPU_TARGET=x86_64
OS_TARGET=win64
COMPILER=ppcrossx64

true "$0: START"

# check if script run as root
if [ "$(id -u)" != "0" ]; then
  true "$0: ERROR: This must be run as root!"
  exit 1
fi

command -v safe-rm >/dev/null

temp_folder="$(mktemp --directory)"

exit_handler() {
  if [ "$temp_folder" = "" ]; then
    return 0
  fi
  if ! test -d "$temp_folder" ; then
    return 0
  fi
  safe-rm --verbose --force --recursive -- "$temp_folder" || true
}

trap exit_handler EXIT

# optional! install requirements
install_dependencies() {
  apt-get install --yes --no-install-recommends make git fpc lazarus
}

install_ppcross() {
  install_ppcross_using_git_from_upstream
  #install_ppcross_using_debian_source_package
}

install_ppcross_using_debian_source_package() {
  mkdir --parents -- "$temp_folder"

  cd -- "$temp_folder"

  apt-get source fpc

  cd -- fpc-*

  ## regenerate Makefile.fpc
  ## https://wiki.freepascal.org/Fpcmake
  #fpcmake -w -Tall
  fpcmake -w -Tx86_64-win64

  make clean all OS_TARGET="$OS_TARGET" CPU_TARGET="$CPU_TARGET"
  make crossinstall OS_TARGET=$OS_TARGET CPU_TARGET="$CPU_TARGET" INSTALL_PREFIX=/usr
  ln -sf "$fpc_version_path/$COMPILER" "/usr/bin/$COMPILER"
}

install_ppcross_using_git_from_upstream() {
  if [ ! -d "/usr/share/fpcsrc" ]; then
    true "$0: ERROR: Cannot find fpc source dir!"
    exit 1
  else
    cd /usr/share/fpcsrc

    fpc_version_path="/usr/lib/fpc/$FPC_VERSION"
    safe-rm --recursive --force -- "$fpc_version_path"
    mkdir --parents "$fpc_version_path"
    cd "$fpc_version_path"

    git init
    git remote add origin https://gitlab.com/freepascal.org/fpc/source.git
    git fetch --depth 1 origin "$FPC_COMMIT_FOR_VERSION"
    git checkout FETCH_HEAD

    make clean all OS_TARGET="$OS_TARGET" CPU_TARGET="$CPU_TARGET"
    make crossinstall OS_TARGET=$OS_TARGET CPU_TARGET="$CPU_TARGET" INSTALL_PREFIX=/usr
    ln -sf "$fpc_version_path/$COMPILER" "/usr/bin/$COMPILER"
  fi
}

# add searchpath for fpc compiler
add_searchpath() {
  if grep "Fu/usr/lib/fpc" /etc/fpc.cfg; then
    true "$0: INFO: /etc/fpc.cfg already contains Fu/usr/lib/fpc"
  else
    sed -i '/^# searchpath for units.*/a -Fu/usr/lib/fpc/$fpcversion/units/$fpctarget/*' /etc/fpc.cfg
  fi
}

case "$1" in
  install_dependencies) install_dependencies;;
  install_ppcross) install_ppcross;;
  add_searchpath) add_searchpath;;
  all)
    install_dependencies
    install_ppcross
    add_searchpath
  ;;
  *)
    true "$0: ERROR: choose either install_dependencies, install_ppcross, add_searchpath or all"
  exit 1
  ;;
esac

true "$0: INFO: END: OK".

exit 0
