#!/bin/bash

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

if [ -f /usr/libexec/helper-scripts/pre.bsh ]; then
   source /usr/libexec/helper-scripts/pre.bsh
fi

set -e

true "
#####################################################################
## INFO: BEGIN: $DPKG_MAINTSCRIPT_PACKAGE $DPKG_MAINTSCRIPT_NAME $@
#####################################################################
"

main_app_dir="/usr/share/sandbox-app-launcher"
auto_dir="/var/cache/sandbox-app-launcher-autogenerated"
appdata_dir="/home/sandbox-app-launcher-appdata"
shared_dir="${appdata_dir}/shared"
wrapper_script_non_wx="${main_app_dir}/wrapper-script"
wrapper_script_wx="${main_app_dir}/wrapper-script-wx"

for dir in "${main_app_dir}" "${auto_dir}" "${appdata_dir}"; do
  if ! [ -d "${dir}" ]; then
    mkdir --parents --mode=755 "${dir}"
  fi
done

if ! [ -d "${shared_dir}" ]; then
  mkdir --parents --mode=1777 "${shared_dir}"
fi

## Cannot use a symlink due to apparmor issues.
## https://github.com/Whonix/sandbox-app-launcher/pull/60#pullrequestreview-678111466
cp "${wrapper_script_non_wx}" "${wrapper_script_wx}"

## Generate seccomp filter.
compiler_flags="-lseccomp -ldl -D_GNU_SOURCE -Wdate-time -D_FORTIFY_SOURCE=3 -g -O2 -fstack-protector-all -Wformat -Werror=format-security -Wl,-z,relro -Wl,-z,now"

"${main_app_dir}/autogen-seccomp" "${main_app_dir}/seccomp-whitelist" > "${auto_dir}/seccomp.c"
"${main_app_dir}/autogen-seccomp" "${main_app_dir}/seccomp-whitelist-wx" > "${auto_dir}/seccomp-wx.c"
str_replace "seccomp-filter.bpf" "seccomp-filter-wx.bpf" "${auto_dir}/seccomp-wx.c" >/dev/null

gcc "${auto_dir}/seccomp.c" -o "${auto_dir}/seccomp" ${compiler_flags}
gcc "${auto_dir}/seccomp-wx.c" -o "${auto_dir}/seccomp-wx" ${compiler_flags}

chmod 700 "${auto_dir}/seccomp" "${auto_dir}/seccomp-wx"
"${auto_dir}/seccomp"
"${auto_dir}/seccomp-wx"

true "INFO: debhelper beginning here."

#DEBHELPER#

true "INFO: Done with debhelper."

true "
#####################################################################
## INFO: END  : $DPKG_MAINTSCRIPT_PACKAGE $DPKG_MAINTSCRIPT_NAME $@
#####################################################################
"

## Explicitly "exit 0", so eventually trapped errors can be ignored.
exit 0
