#!/bin/sh

# Helper to emulate --reference for BusyBox compatibility
copy_metadata() {
  reference="$1"
  target="$2"

  if [ -e "$reference" ] && [ -e "$target" ]; then
    # Get numeric UID:GID and octal permissions
    owner=$(stat -c "%u:%g" "$reference" 2>/dev/null)
    perm=$(stat -c "%a" "$reference" 2>/dev/null)

    if [ -n "$owner" ]; then
      chown "$owner" "$target" 2>/dev/null || true
    fi
    if [ -n "$perm" ]; then
      chmod "$perm" "$target" 2>/dev/null || true
    fi
  fi
}

config() {
  NEW="$1"
  OLD="$(dirname "$NEW")/$(basename "$NEW" .new)"

  if [ ! -r "$OLD" ]; then
    # No old file exists, just move the new signed file into place
    mv "$NEW" "$OLD"
  elif [ "$(cat "$OLD" | md5sum)" = "$(cat "$NEW" | md5sum)" ]; then
    # Contents match. We MUST use the new file to get the IMA signature,
    # but we preserve the old file's permissions and ownership.
    copy_metadata "$OLD" "$NEW"
    mv -f "$NEW" "$OLD"
  fi
  # If contents differ, we leave the .new file for the admin to review.
}

preserve_perms() {
  NEW="$1"
  OLD="$(dirname "$NEW")/$(basename "$NEW" .new)"

  if [ -e "$OLD" ]; then
    # Copy the NEW file (which has the security.ima xattr) to .incoming.
    # The old script copied $OLD here, which stripped the signature!
    cp -a "$NEW" "${NEW}.incoming"

    # Apply the old file's permissions/ownership to the incoming file
    copy_metadata "$OLD" "${NEW}.incoming"

    # Replace $NEW with the correctly permissioned, signed file
    mv "${NEW}.incoming" "$NEW"
  fi
  config "$NEW"
}

# Create the tor account if it does not already exist.
if ! grep -q "^tor:" etc/group 2>/dev/null; then
  echo "tor:x:220:" >> etc/group
fi
if ! grep -q "^tor:" etc/passwd 2>/dev/null; then
  echo "tor:x:220:220:The Onion Router:/dev/null:/bin/false" >> etc/passwd
fi
if ! grep -q "^tor:" etc/shadow 2>/dev/null; then
  echo "tor:!::0:::::" >> etc/shadow
fi

# Defensive: log and state dirs.
[ -d var/lib/tor ] && chown 220:220 var/lib/tor 2>/dev/null || true
[ -d var/lib/tor ] && chmod 0700 var/lib/tor 2>/dev/null || true
[ -d var/log/tor ] && chown 220:220 var/log/tor 2>/dev/null || true
[ -d var/run/tor ] && chown 220:220 var/run/tor 2>/dev/null || true

EDITION=""
if [ -r etc/amos/edition ]; then
  EDITION=$(cat etc/amos/edition 2>/dev/null | tr -d '[:space:]')
fi

if [ "$EDITION" = "edge" ]; then
  mkdir -p var/lib/tor-edge
  chown 220:220 var/lib/tor-edge
  chmod 0700 var/lib/tor-edge
  preserve_perms etc/rc.d/rc.tor-edge.new
  config etc/tor/torrc.edge.new
else
  rm -f etc/rc.d/rc.tor-edge.new
  rm -f etc/tor/torrc.edge.new
fi

preserve_perms etc/rc.d/rc.tor.new
config etc/tor/torrc.new
config etc/logrotate.d/tor.new