#!/bin/sh
set -eu

checkout=${1:?usage: sh repro.sh CHECKOUT}
installer=$checkout/scripts/install.sh
if [ ! -f "$installer" ]; then echo 'RESULT: inconclusive'; exit 2; fi

python3 --version
curl --version | head -n 1
tar --version | head -n 1
uname -srm

work=$(mktemp -d)
server_pid=
cleanup() {
  if [ -n "$server_pid" ]; then kill "$server_pid" 2>/dev/null || :; wait "$server_pid" 2>/dev/null || :; fi
  rm -rf "$work"
}
trap cleanup 0
mkdir -p "$work/tmp" "$work/home"
export TMPDIR=$work/tmp HOME=$work/home

case $(uname -s) in Darwin) platform=darwin ;; Linux) platform=linux ;; *) echo 'RESULT: inconclusive'; exit 2 ;; esac
case $(uname -m) in arm64|aarch64) arch=arm64 ;; x86_64|amd64) arch=x64 ;; *) echo 'RESULT: inconclusive'; exit 2 ;; esac
if [ "$platform-$arch" = darwin-x64 ]; then echo 'RESULT: inconclusive'; exit 2; fi
archive=t3-1.2.3-$platform-$arch.tar.gz

cat > "$work/fixture.py" <<'PY'
import hashlib
import io
import pathlib
import sys
import tarfile
from http.server import BaseHTTPRequestHandler, HTTPServer

root = pathlib.Path(sys.argv[1])
archive = sys.argv[2]
program = b'#!/bin/sh\necho fixture-1.2.3\n'
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode='w:gz') as tar:
    info = tarfile.TarInfo(archive[:-7] + '/t3')
    info.mode = 0o755
    info.size = len(program)
    tar.addfile(info, io.BytesIO(program))
data = buffer.getvalue()
checksums = f'{hashlib.sha256(data).hexdigest()}  {archive}\n'.encode()

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path.endswith('/SHA256SUMS'):
            body, code = checksums, 200
        elif self.path.startswith('/good/') and self.path.endswith('/' + archive):
            body, code = data, 200
        else:
            body, code = b'', 404
        self.send_response(code)
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)
    def log_message(self, *_args):
        pass

server = HTTPServer(('127.0.0.1', 0), Handler)
(root / 'port').write_text(str(server.server_port))
server.serve_forever()
PY
python3 "$work/fixture.py" "$work" "$archive" &
server_pid=$!
i=0
while [ ! -s "$work/port" ]; do
  i=$((i + 1))
  if [ "$i" -ge 100 ]; then echo 'RESULT: inconclusive'; exit 2; fi
  sleep 0.05
done
origin=http://127.0.0.1:$(cat "$work/port")

run_install() {
  name=$1
  mkdir -p "$work/$name"
  if T3CODE_VERSION=1.2.3 T3CODE_RELEASE_BASE_URL=$origin/$name \
      T3CODE_HOME=$work/$name/state T3CODE_INSTALL_BIN_DIR=$work/$name/bin \
      sh "$installer" > "$work/$name/stdout" 2> "$work/$name/stderr"; then
    result=0
  else
    result=$?
  fi
}

run_install good
if [ "$result" -ne 0 ] || [ ! -f "$work/good/state/runtime/versions/1.2.3/.install-complete" ]; then
  echo "control failed: exit $result"
  cat "$work/good/stderr"
  echo 'RESULT: inconclusive'
  exit 2
fi
run_install missing
echo "missing archive: exit $result"
cat "$work/missing/stderr"
if [ "$result" -ne 0 ] && ! grep -q 't3 install:' "$work/missing/stderr"; then
  echo 'RESULT: defect reproduced'
  exit 1
fi
if [ "$result" -ne 0 ] && grep -q 't3 install:' "$work/missing/stderr"; then
  echo 'RESULT: expected behavior'
  exit 0
fi
echo 'RESULT: inconclusive'
exit 2
