#!/bin/bash
set -euo pipefail
umask 077
source_dir="$(cd -- "$(dirname -- "$0")" && pwd)"
if [[ "$(uname -s)" != Darwin ]]; then
  printf 'This installer is for macOS only.\n' >&2; exit 1
fi
brew_bin="$(command -v brew || true)"
if [[ -z "$brew_bin" ]]; then
  for candidate in /opt/homebrew/bin/brew /usr/local/bin/brew; do
    if [[ -x "$candidate" ]]; then brew_bin="$candidate"; break; fi
  done
fi
if [[ -z "$brew_bin" ]]; then
  printf 'Install Homebrew from https://brew.sh first, then rerun this script.\n' >&2
  exit 1
fi
"$brew_bin" install openconnect ocproxy python@3.14
if [[ ! -d '/Applications/Clash Verge.app' ]]; then
  "$brew_bin" install --cask clash-verge-rev
fi
brew_prefix="$("$brew_bin" --prefix)"
export PATH="$brew_prefix/bin:$brew_prefix/sbin:/usr/bin:/bin:/usr/sbin:/sbin"
python_bin="$brew_prefix/opt/python@3.14/bin/python3.14"
target="$HOME/Library/Application Support/CUHK-VPN"
mkdir -p "$target/state"
"$python_bin" - "$target" <<'CHECK'
import fcntl, pathlib, sys
p=pathlib.Path(sys.argv[1])/'state/background.lock'
with p.open('a+') as f:
    try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        sys.exit('The helper is running. Run autostart.sh stop before reinstalling.')
CHECK
read -r -p 'CUHK(SZ) username / student ID (without email suffix): ' vpn_account
if [[ -z "$vpn_account" ]]; then printf 'An account is required.\n' >&2; exit 1; fi
cp "$source_dir/background.py" "$source_dir/clash-script.js" "$source_dir/base-profile.yaml" "$target/"
"$python_bin" - "$target" "$python_bin" "$vpn_account" "$(command -v openconnect)" "$(command -v ocproxy)" <<'PY'
import json, pathlib, shlex, sys
root=pathlib.Path(sys.argv[1]); python=sys.argv[2]
settings={"account":sys.argv[3],"openconnect":sys.argv[4],"ocproxy":sys.argv[5]}
(root/'settings.json').write_text(json.dumps(settings,indent=2)+'\n')
bridge='#!/bin/bash\nset -e\nexec '+shlex.quote(settings['ocproxy'])+' -D 11080\n'
(root/'bridge.sh').write_text(bridge)
starter='#!/bin/bash\nset -eu\numask 077\n'
starter+='mkdir -p '+shlex.quote(str(root/'state'))+'\n'
command=shlex.quote(python)+' '+shlex.quote(str(root/'background.py'))
starter+='case "${1:-start}" in\n'
starter+='  stop|status) exec '+command+' "$1" ;;\n'
starter+='  restart) '+command+' stop ;;\n'
starter+='  start) ;;\n'
starter+='  *) echo "Usage: autostart.sh [start|stop|restart|status]" >&2; exit 2 ;;\nesac\n'
starter+='/usr/bin/nohup '+command+' run'
starter+=' </dev/null >>'+shlex.quote(str(root/'state/autostart.log'))+' 2>&1 &\nexit 0\n'
(root/'autostart.sh').write_text(starter)
for name in ('bridge.sh','autostart.sh','background.py'): (root/name).chmod(0o700)
PY
printf '\nSave your SCHOOL VPN password when prompted below. It will not be echoed.\n'
/usr/bin/security add-generic-password -a "$vpn_account" -s cuhksz-vpn-cli \
  -l 'CUHK(SZ) VPN CLI' -T /usr/bin/security -U -w
printf '\nInstalled in: %s\n' "$target"
printf 'Next: complete the Clash settings described in the article.\n'
/usr/bin/open "$target"
