#!/bin/bash
# Installs controller files only. No systemctl start/stop, no gateways, no GPUs.
set -euo pipefail
umask 077
source_dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
target_dir=/home/lab/bench/ornith/modular/control
link_path=/home/lab/.local/bin/ornithctl
expected_target=$target_dir/ornithctl.py
if [ "$(id -un)" != lab ] || [ "$(id -u)" != 1000 ]; then
  echo 'Refusing install: expected lab uid1000.' >&2
  exit 1
fi
if [ -L "$target_dir" ]; then
  echo 'Refusing symlinked target directory.' >&2
  exit 1
fi
if [ -e "$link_path" ] || [ -L "$link_path" ]; then
  if [ ! -L "$link_path" ] || [ "$(readlink -- "$link_path")" != "$expected_target" ]; then
    echo 'ornithctl already exists with a different target; inspect before replacing.' >&2
    exit 1
  fi
fi
for file in ornithctl.py ornith_gateway.py test_control.py README.md install.sh; do
  test -f "$source_dir/$file"
done
# Run the fixture suite before changing the installed controller. This launches
# only fake HTTP servers on ephemeral localhost ports and mocks systemd calls.
(cd "$source_dir" && /usr/bin/env -i PATH=/usr/bin:/bin HOME=/home/lab LANG=C.UTF-8 python3 -I -c \
  'import sys,unittest; sys.path.insert(0,"."); result=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.discover(".",pattern="test_control.py")); sys.exit(not result.wasSuccessful())')
install -d -m 755 "$target_dir" /home/lab/.local/bin
backup_dir=''
for file in ornithctl.py ornith_gateway.py test_control.py README.md install.sh; do
  if [ -L "$target_dir/$file" ]; then
    echo "Refusing symlinked installed file: $file" >&2
    exit 1
  fi
  if [ -e "$target_dir/$file" ] && ! cmp -s "$source_dir/$file" "$target_dir/$file"; then
    if [ -z "$backup_dir" ]; then
      install -d -m 700 /home/lab/bench/ornith/modular/control-backups
      backup_dir=$(mktemp -d /home/lab/bench/ornith/modular/control-backups/install-XXXXXXXX)
    fi
    cp -p -- "$target_dir/$file" "$backup_dir/$file"
  fi
done
for file in ornithctl.py ornith_gateway.py test_control.py README.md install.sh; do
  if ! cmp -s "$source_dir/$file" "$target_dir/$file"; then
    temp_file=$(mktemp "$target_dir/.install-XXXXXXXX")
    install -m 644 "$source_dir/$file" "$temp_file"
    if [ "$file" = ornithctl.py ] || [ "$file" = install.sh ]; then chmod 755 "$temp_file"; fi
    mv -f -- "$temp_file" "$target_dir/$file"
  fi
done
if [ ! -L "$link_path" ]; then ln -s -- "$expected_target" "$link_path"; fi
echo 'Controller installed. No live units or processes were changed.'
if [ -n "$backup_dir" ]; then printf 'Previous code backup: %s\n' "$backup_dir"; fi
