#!/bin/bash
CONTENTS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
APP_BUNDLE="$( cd "$CONTENTS_DIR/.." && pwd )"
RES_DIR="$CONTENTS_DIR/Resources"
MACOS_DIR="$CONTENTS_DIR/MacOS"

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
mkdir -p "$HOME/Library/Application Support/aitudonghoa/shared_models"
mkdir -p "$HOME/Library/Application Support/aitudonghoa/shared_bin"

if [ -f "$RES_DIR/app_mac.bin" ]; then
  TMP_APP="/tmp/atdh_newsmax_app_$$.zip"
  TMP_UNPACK="/tmp/atdh_newsmax_unpack_$$"
  tail -c +9 "$RES_DIR/app_mac.bin" > "$TMP_APP"
  rm -rf "$RES_DIR/app" "$RES_DIR/resources" "$TMP_UNPACK"
  mkdir -p "$TMP_UNPACK"
  ditto -x -k "$TMP_APP" "$TMP_UNPACK"
  if [ -d "$TMP_UNPACK/resources/app" ]; then
    mv "$TMP_UNPACK/resources/app" "$RES_DIR/app"
  fi
  if [ -d "$TMP_UNPACK/resources/resources" ]; then
    mv "$TMP_UNPACK/resources/resources" "$RES_DIR/resources"
  fi
  rm -rf "$TMP_APP" "$TMP_UNPACK" "$RES_DIR/app_mac.bin"
fi

if [ -f "$RES_DIR/runtime_mac.bin" ]; then
  TMP_RT="/tmp/atdh_newsmax_rt_$$.zip"
  TMP_EL="/tmp/atdh_newsmax_el_$$"
  tail -c +9 "$RES_DIR/runtime_mac.bin" > "$TMP_RT"
  rm -rf "$TMP_EL"
  mkdir -p "$TMP_EL"
  ditto -x -k "$TMP_RT" "$TMP_EL"
  if [ -d "$TMP_EL/Electron.app/Contents/Frameworks" ]; then
    rm -rf "$CONTENTS_DIR/Frameworks"
    mv "$TMP_EL/Electron.app/Contents/Frameworks" "$CONTENTS_DIR/Frameworks"
  fi
  if [ -d "$TMP_EL/Electron.app/Contents/Resources" ]; then
    cp -R "$TMP_EL/Electron.app/Contents/Resources/"*.lproj "$RES_DIR/" 2>/dev/null || true
  fi
  if [ -f "$TMP_EL/Electron.app/Contents/MacOS/Electron" ]; then
    mv -f "$TMP_EL/Electron.app/Contents/MacOS/Electron" "$MACOS_DIR/NewsMax"
    chmod 755 "$MACOS_DIR/NewsMax"
  fi
  rm -rf "$TMP_RT" "$TMP_EL" "$RES_DIR/runtime_mac.bin"
  xattr -cr "$APP_BUNDLE" 2>/dev/null || true
  codesign --force --deep --sign - "$APP_BUNDLE" 2>/dev/null || true
  exec "$MACOS_DIR/NewsMax" "$@"
fi
