#!/bin/sh
# usage <version> <classfile>
# Check that .class file's version is <= the specified version.
# This ensures that the class will run on a particular version of Java.
# For example,
#   classfile_check_version 49 MyClass.class
# checks that the classfile will not run in a 1.5 JVM (1.6 classfiles are version 50).
# For all class file format version numbers, see
#   http://en.wikipedia.org/wiki/Class_(file_format)

## TODO: perhaps use plume/ClassFileVersion.java instead.

set -eu

if [ "$#" -ne 2 ]; then
  echo "Should be two arguments (version classfile)"
  exit 1
fi

if [ ! -e "$2" ]; then
  echo "$2 does not exist"
  exit 1
fi

# The first 8 bytes of a .class file are the magic number 0xcafebabe, the
# 2-byte minor version, and the 2-byte major version, as 16 hexadecimal
# digits.  A file with fewer than 8 bytes yields a shorter string.
header="$(xxd -l 8 -p "$2" | tr -d '\n')"
magic="$(printf '%s' "$header" | cut -c 1-8)"
major="$(printf '%s' "$header" | cut -c 13-16)"

if [ "${#header}" -ne 16 ] || [ "$magic" != "cafebabe" ]; then
  echo "$2 is not a Java class file"
  exit 1
fi

# bc needs hex values in upper case.
HEAD="$(printf '%s' "$major" | tr '[:lower:]' '[:upper:]')"
version="$(echo "ibase=16; $HEAD" | bc)"

if [ "$version" -gt "$1" ]; then
  echo "$2 has version $version"
  exit 1
fi
exit 0
