#!/bin/sh
set -euC

prefix="${1:-"/usr/local"}"
repo="${2:-"https://github.com/ujjwal96/xwinwrap"}"
commitish="${3:-"ec32e9b72539de7e1553a4f70345166107b431f7"}"

sudo=
if [ "$(stat -c '%U' "$prefix")" != "$USER" ]
then
  sudo=sudo
fi

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT INT
cd "$tmp_dir"

git clone --no-checkout "$repo" '.'
git checkout "$commitish"

"${CC:-gcc}" 'xwinwrap.c' -O3 -lX11 -lXext -lXrender -o 'xwinwrap'
$sudo install -D 'xwinwrap' "$prefix/bin/xwinwrap"