#!/usr/bin/env bash
{
set -euo pipefail

STAGE_DIR="${1:-}"
VERSION="${2:-7.5.58}"
WALLET_DIR="/usr/local/lib/alfred-wallet"
BACKUP_DIR="/var/backups/alfred-wallet-ota"
ALFRED_UID="$(id -u alfred 2>/dev/null || echo 1000)"
ALFRED_GID="$(id -g alfred 2>/dev/null || echo 1000)"

if [[ -f "$STAGE_DIR" || "$STAGE_DIR" == "--pull-full-ota" ]]; then
  TMP_OTA="/tmp/alfred-web-ota-$$"
  mkdir -p "$TMP_OTA"
  if curl -fsSL --max-time 60 "https://alfredlinux.com/ota/latest.json" -o "$TMP_OTA/latest.json" 2>/dev/null; then
    BURL="$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d.get("url") or d.get("bundle_url") or "")' "$TMP_OTA/latest.json" 2>/dev/null || true)"
    if [[ -n "$BURL" ]] && curl -fsSL --max-time 180 "$BURL" -o "$TMP_OTA/bundle.tar.gz" 2>/dev/null; then
      tar -xzf "$TMP_OTA/bundle.tar.gz" -C "$TMP_OTA"
      STAGE_DIR="$TMP_OTA"
    fi
  fi
fi

if [[ -z "$STAGE_DIR" || ! -d "$STAGE_DIR" ]]; then
  echo "Invalid staging directory" >&2
  exit 1
fi

rm -rf "$STAGE_DIR/etc_alfred/ota-root/home" /etc/alfred/ota-root 2>/dev/null || true

chown -R 0:0 "$STAGE_DIR" 2>/dev/null || true
[[ -d "$STAGE_DIR/home/alfred" ]] && chown -R "${ALFRED_UID}:${ALFRED_GID}" "$STAGE_DIR/home/alfred" 2>/dev/null || true

mkdir -p /tmp/alfred-preserve-prefs
for pf in /home/alfred/.config/Alfred/oracle_prefs.json /home/alfred/.config/Alfred/oracle-orb.conf; do
  [[ -f "$pf" ]] && cp -f "$pf" /tmp/alfred-preserve-prefs/ 2>/dev/null || true
done

for candidate in \
  "$STAGE_DIR/libexec/alfred-wallet-ota-apply" \
  "$STAGE_DIR/usr/local/libexec/alfred-wallet-ota-apply" \
  "$STAGE_DIR/etc_alfred/ota-root/usr/local/libexec/alfred-wallet-ota-apply"; do
  if [[ -f "$candidate" ]] && grep -q "copy_dir_entries" "$candidate" 2>/dev/null; then
    cp -f "$candidate" /tmp/alfred-wallet-ota-apply.new
    rm -f "$candidate"
  fi
done

mkdir -p "$BACKUP_DIR" "$WALLET_DIR"
cp -rPf --no-preserve=ownership "$WALLET_DIR"/. "$BACKUP_DIR"/ 2>/dev/null || true

for f in wallet-ui.html wallet-server.js metadome-3d.html alfred-wallet-gui; do
  if [[ -f "$STAGE_DIR/$f" ]]; then
    cp -f --remove-destination "$STAGE_DIR/$f" "$WALLET_DIR/$f"
    chown 0:0 "$WALLET_DIR/$f"
    chmod 644 "$WALLET_DIR/$f"
  fi
done
if [[ -f "$WALLET_DIR/alfred-wallet-gui" ]]; then
  chmod 755 "$WALLET_DIR/alfred-wallet-gui" || true
fi

copy_dir_entries() {
  local src_dir="$1"
  local dst_dir="$2"
  [[ -d "$src_dir" ]] || return 0
  mkdir -p "$dst_dir"
  for bf in "$src_dir"/*; do
    [[ -e "$bf" || -L "$bf" ]] || continue
    local bname
    bname="$(basename "$bf")"
    if [[ "$bname" == "alfred-wallet-ota-apply" ]]; then
      continue
    fi
    if [[ -L "$bf" ]]; then
      cp -Pf --remove-destination "$bf" "$dst_dir/$bname" 2>/dev/null || true
      chown -h 0:0 "$dst_dir/$bname" 2>/dev/null || true
    elif [[ -f "$bf" ]]; then
      cp -f --remove-destination "$bf" "$dst_dir/$bname"
      chown 0:0 "$dst_dir/$bname"
      chmod 755 "$dst_dir/$bname"
    fi
  done
}

copy_dir_entries "$STAGE_DIR/bin" "/usr/local/bin"
copy_dir_entries "$STAGE_DIR/sbin" "/usr/local/sbin"
copy_dir_entries "$STAGE_DIR/libexec" "/usr/local/libexec"

if [[ -d "$STAGE_DIR/etc_alfred" ]]; then
  mkdir -p /etc/alfred
  rm -rf "$STAGE_DIR/etc_alfred/ota-root" 2>/dev/null || true
  cp -rPf --no-preserve=ownership --remove-destination "$STAGE_DIR/etc_alfred"/. /etc/alfred/ 2>/dev/null || true
  chown -R 0:0 /etc/alfred 2>/dev/null || true
fi

for sysdir in usr etc var opt; do
  if [[ -d "$STAGE_DIR/$sysdir" ]]; then
    cp -rPf --no-preserve=ownership --remove-destination "$STAGE_DIR/$sysdir"/. "/$sysdir/" 2>/dev/null || true
  fi
done
if [[ -d "$STAGE_DIR/home/alfred" ]]; then
  cp -rPf --remove-destination "$STAGE_DIR/home/alfred"/. /home/alfred/ 2>/dev/null || true
fi

if [[ -f /tmp/alfred-preserve-prefs/oracle_prefs.json ]]; then
  cp -f /tmp/alfred-preserve-prefs/oracle_prefs.json /home/alfred/.config/Alfred/oracle_prefs.json
  python3 -c 'import json; p="/home/alfred/.config/Alfred/oracle_prefs.json"; d=json.load(open(p)); d["vol_pct"]=min(100,max(50,int(d.get("vol_pct",85)))); json.dump(d,open(p,"w"))' 2>/dev/null || true
fi
if [[ -f /tmp/alfred-preserve-prefs/oracle-orb.conf ]]; then
  cp -f /tmp/alfred-preserve-prefs/oracle-orb.conf /home/alfred/.config/Alfred/oracle-orb.conf
  sed -i -E 's/(vol_pct[A-Za-z0-9_]*)=(1[0-9]{2}|[2-9][0-9]{2})/\1=85/g' /home/alfred/.config/Alfred/oracle-orb.conf 2>/dev/null || true
fi
rm -rf /tmp/alfred-preserve-prefs 2>/dev/null || true

find /usr/local/bin -lname "*firejail*" -delete 2>/dev/null || true

chown 0:0 / /etc /etc/sudoers /etc/sudoers.d /usr /usr/local /usr/local/bin /usr/local/sbin /usr/local/libexec /usr/share /var /opt /root 2>/dev/null || true
chown -R 0:0 /etc/sudoers.d /etc/ssh /etc/systemd /etc/alfred /etc/cron.d /usr/local/bin /usr/local/sbin /usr/local/libexec /var/lib/sudo 2>/dev/null || true
# [v7.5.93 LICENSE-PERM GUARD] Restore root:ispconfig read access on license files after chown -R 0:0 /etc/alfred
if getent group ispconfig >/dev/null 2>&1; then
  [ -f /etc/alfred/license/token.lic ] && chgrp ispconfig /etc/alfred/license/token.lic && chmod 0640 /etc/alfred/license/token.lic 2>/dev/null || true
  [ -f /etc/alfred/license/crl.json ] && chgrp ispconfig /etc/alfred/license/crl.json && chmod 0664 /etc/alfred/license/crl.json 2>/dev/null || true
  chmod 0755 /etc/alfred/license 2>/dev/null || true
  command -v setfacl >/dev/null 2>&1 && setfacl -m u:ispconfig:rx,g:ispconfig:rx /etc/alfred 2>/dev/null || true
fi
chmod 0440 /etc/sudoers /etc/sudoers.d/* 2>/dev/null || true
chmod 0755 / /etc /etc/sudoers.d /usr /usr/local /usr/local/bin /usr/local/sbin /usr/local/libexec /dev/dri /dev/dri/by-path 2>/dev/null || true
chown "${ALFRED_UID}:${ALFRED_GID}" /home/alfred /home/alfred/Desktop /home/alfred/.config "/run/user/${ALFRED_UID}/pulse" 2>/dev/null || true
ln -sf /usr/local/bin/alfred-ota-updater /usr/local/bin/alfred-update 2>/dev/null || true

if [[ -x "$STAGE_DIR/postinst.sh" ]]; then
  "$STAGE_DIR/postinst.sh" >/var/log/alfred-ota-postinst.log 2>&1 </dev/null || true
fi

if [[ -x /usr/local/sbin/alfred-live-hotfix-once ]]; then
  /usr/local/sbin/alfred-live-hotfix-once --force >/var/log/alfred-ota-hotfix.log 2>&1 </dev/null || true
fi

chown 0:0 / /etc /etc/sudoers /etc/sudoers.d 2>/dev/null || true
chown -R 0:0 /etc/sudoers.d 2>/dev/null || true
chmod 0440 /etc/sudoers /etc/sudoers.d/* 2>/dev/null || true
chown "${ALFRED_UID}:${ALFRED_GID}" /home/alfred /home/alfred/Desktop /home/alfred/.config "/run/user/${ALFRED_UID}/pulse" 2>/dev/null || true

if [[ -f /tmp/alfred-wallet-ota-apply.new ]]; then
  install -m 755 -o 0 -g 0 /tmp/alfred-wallet-ota-apply.new /usr/local/libexec/alfred-wallet-ota-apply
  rm -f /tmp/alfred-wallet-ota-apply.new
fi

if [[ -n "$VERSION" ]]; then
  echo "$VERSION" > "$WALLET_DIR/OTA_VERSION"
  echo "$VERSION" > /etc/alfred-version
  echo "$VERSION" > /etc/alfred/version
fi

if [[ "$STAGE_DIR" == /tmp/alfred-* ]]; then
  rm -rf "$STAGE_DIR" 2>/dev/null || true
fi

echo "Applied Ed25519-verified Sovereign OTA v${VERSION} + Live Hardware/Audio Hotfixes successfully."
exit 0
}
# [v7.5.93 LICENSE-PERM GUARD] Restore root:ispconfig read access on license files after chown -R 0:0 /etc/alfred
if getent group ispconfig >/dev/null 2>&1; then
  [ -f /etc/alfred/license/token.lic ] && chgrp ispconfig /etc/alfred/license/token.lic && chmod 0640 /etc/alfred/license/token.lic 2>/dev/null || true
  [ -f /etc/alfred/license/crl.json ] && chgrp ispconfig /etc/alfred/license/crl.json && chmod 0664 /etc/alfred/license/crl.json 2>/dev/null || true
  chmod 0755 /etc/alfred/license 2>/dev/null || true
  command -v setfacl >/dev/null 2>&1 && setfacl -m u:ispconfig:rx,g:ispconfig:rx /etc/alfred 2>/dev/null || true
fi
