#!/bin/bash
# Recreate koopa-tor-relay as non-root (uid 1000) under rootless podman keep-id.
# Run as hernani on koopa (not root). Stops/removes existing container first.
set -euo pipefail

NAME=koopa-tor-relay
IMAGE="${TOR_IMAGE:-localhost/koopa-tor-relay:latest}"
BASE="${KOOPA_TOR_BASE:-$HOME/koopa-tor-relay}"

if [[ ! -f "$BASE/torrc" ]]; then
  echo "ERROR: missing $BASE/torrc" >&2
  exit 1
fi
mkdir -p "$BASE/data" "$BASE/log"
# Host ownership: hernani (uid 1000) ↔ container debian-tor (uid 1000) via keep-id
chmod 700 "$BASE/data" 2>/dev/null || true

if podman ps -a --format '{{.Names}}' | grep -qx "$NAME"; then
  podman stop "$NAME" 2>/dev/null || true
  podman rm "$NAME"
fi

podman create \
  --name "$NAME" \
  --replace \
  --network host \
  --user 1000:1000 \
  --userns keep-id \
  --restart unless-stopped \
  -v "$BASE/torrc:/etc/tor/torrc:ro" \
  -v "$BASE/data:/var/lib/tor:Z" \
  -v "$BASE/log:/var/log/tor:Z" \
  --label org.hacktivism.service=tor \
  --label org.hacktivism.container=koopa-tor-relay \
  --label org.hacktivism.managed_by=koopa-admin \
  "$IMAGE"

echo "created $NAME (user 1000:1000, userns=keep-id, host net)"
echo "start: podman start $NAME   # or systemctl --user start container-koopa-tor-relay"
