#!/bin/sh
#
# Repackage a rustdesk .deb so that after installation it connects to your own
# hbbs/hbbr server instead of the hardcoded official defaults. The binary keeps
# rs-ny.rustdesk.com / RS_PUB_KEY only as fallback (config.rs get_rendezvous_server,
# common.rs get_key); this script bakes a `custom-rendezvous-server` + `key`
# (and optional `relay-server`) into every user's config via the postinst.
#
# The values land in $HOME/.config/rustdesk/RustDesk2.toml ([options]) for all
# existing users plus /etc/skel, so future accounts get them too. Files written
# by the root postinst are chowned to each home's owner, since RustDesk runs as
# the user and would otherwise be unable to read/write a root-owned 0600 config.
#
# Usage:
#   ./set_custom_server.sh --host HOST[:PORT] --key BASE64KEY [--relay HOST[:PORT]] [-o OUT.deb] INPUT.deb
#
# Options:
#   --host HOST[:PORT]   your hbbs rendezvous server (port 21116 implied if omitted)
#   --key  BASE64KEY     hbbs public key (base64)
#   --relay HOST[:PORT]  hbbr relay server (optional; inferred from --host if omitted)
#   -o, --output FILE    output deb path (default: INPUT-custom.deb)
#   -h, --help           show this help
#
# All scratch dirs live under build/ inside this repo.

set -eu

REPO_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$REPO_ROOT"

usage() {
  cat <<EOF
Usage: $0 --host HOST[:PORT] --key BASE64KEY [--relay HOST[:PORT]] [-o OUT.deb] INPUT.deb
EOF
}

host=""
key=""
relay=""
output=""
input=""

while [ "$#" -gt 0 ]; do
  case "$1" in
    --host)
      if [ "$#" -lt 2 ]; then echo "error: --host needs a value" >&2; exit 1; fi
      host="$2"; shift 2
      ;;
    --key)
      if [ "$#" -lt 2 ]; then echo "error: --key needs a value" >&2; exit 1; fi
      key="$2"; shift 2
      ;;
    --relay)
      if [ "$#" -lt 2 ]; then echo "error: --relay needs a value" >&2; exit 1; fi
      relay="$2"; shift 2
      ;;
    -o|--output)
      if [ "$#" -lt 2 ]; then echo "error: --output needs a value" >&2; exit 1; fi
      output="$2"; shift 2
      ;;
    -h|--help) usage; exit 0 ;;
    *)
      if [ -n "$input" ]; then echo "error: unexpected argument: $1" >&2; exit 1; fi
      input="$1"; shift
      ;;
  esac
done

if [ -z "$input" ] || [ -z "$host" ] || [ -z "$key" ]; then
  echo "error: INPUT.deb, --host and --key are required" >&2
  usage >&2
  exit 1
fi
if [ ! -f "$input" ]; then
  echo "error: $input not found" >&2
  exit 1
fi
if ! command -v dpkg-deb >/dev/null 2>&1; then
  echo "error: dpkg-deb not found - this only works on Debian/Ubuntu-like hosts" >&2
  exit 1
fi

if [ -z "$output" ]; then
  output="${input%.deb}-custom.deb"
fi

work="$REPO_ROOT/build/repackage-$$"
mkdir -p "$work"
trap 'rm -rf "$work"' EXIT

dpkg-deb -R "$input" "$work"

postinst="$work/DEBIAN/postinst"
if [ ! -f "$postinst" ]; then
  printf '#!/bin/sh\nset -e\n' > "$postinst"
fi

# Drop any previously baked block so re-running (e.g. with new values) replaces it.
sed -i '/^# --- BEGIN baked by set_custom_server.sh ---$/,/^# --- END baked by set_custom_server.sh ---$/d' "$postinst"

cat >> "$postinst" <<'EOF'

# --- BEGIN baked by set_custom_server.sh ---
if [ "$1" = configure ]; then
    for base in /etc/skel /home/*; do
        [ -d "$base" ] || continue
        dir="$base/.config/rustdesk"
        mkdir -p "$dir"
        cat > "$dir/RustDesk2.toml" <<'CFG'
[options]
custom-rendezvous-server = "__HOST__"
key = "__KEY__"
__RELAY__
CFG
        chmod 600 "$dir/RustDesk2.toml"
        # Written by root, but must be owned by the account that runs RustDesk.
        # /etc/skel stays root-owned; useradd/adduser chowns it to new accounts.
        if [ "$base" != "/etc/skel" ]; then
            owner=$(stat -c %u "$base")
            chown -R "$owner":"$owner" "$dir"
        fi
    done
fi
# --- END baked by set_custom_server.sh ---
EOF

sed -i "s|__HOST__|$host|g; s|__KEY__|$key|g" "$postinst"
if [ -n "$relay" ]; then
  sed -i "s|__RELAY__|relay-server = \"$relay\"|" "$postinst"
else
  sed -i "/__RELAY__/d" "$postinst"
fi
chmod 755 "$postinst"

dpkg-deb --root-owner-group -b "$work" "$output"
echo "Wrote $output (host=$host, key set, relay=${relay:-<inferred>})"