#!/bin/sh

# SPDX-FileCopyrightText: Copyright 2026 Daniel Hast
#
# SPDX-License-Identifier: Apache-2.0 OR MIT

set -eu

if [ "$(id -u)" != 0 ]; then
  echo 'This script must be run as root; exiting.'
  exit 1
elif ! [ -x /usr/bin/brew-proxy ] || ! [ -x /usr/libexec/brew-proxy/brew-proxy-daemon ]; then
  echo 'brew-proxy executables missing; exiting.'
  exit 1
elif ! [ -L /home/linuxbrew/.linuxbrew/bin/brew ]; then
  echo '/home/linuxbrew/.linuxbrew/bin/brew is not a symbolic link; exiting.'
  exit 1
elif [ -e /home/linuxbrew/.linuxbrew/proxy ]; then
  echo '/home/linuxbrew/.linuxbrew/proxy already exists; exiting.'
  exit 1
fi

echo 'Patching brew to use brew-proxy for non-linuxbrew users...'
mkdir /home/linuxbrew/.linuxbrew/proxy
mv /home/linuxbrew/.linuxbrew/bin/brew /home/linuxbrew/.linuxbrew/proxy/brew-original
install -m 755 /usr/libexec/brew-proxy/brew-proxy-dispatch.sh /home/linuxbrew/.linuxbrew/bin/brew

echo 'Changing /home/linuxbrew ownership to linuxbrew user...'
chown -R linuxbrew:linuxbrew /home/linuxbrew

echo 'Setting permissions for /home/linuxbrew...'
chmod -R u=rwX,g=rX,o=rX /home/linuxbrew

echo 'brew-proxy setup complete.'
