#! /bin/sh

# v4l1 v1.0
# Run a program vith v4l1 compatibility library preloaded
# Copyright (c) 2016 Raphaël Halimi <raphael.halimi@gmail.com>

# Source shell-script-helper
. /lib/shell-script-helper


#
# Variables
#

# Configuration files
SYSTEM_CONFIG_FILE="/etc/$(basename "$0").conf"
USER_CONFIG_FILE="$HOME/.$(basename "$0").conf"

# Options defaults
#VERBOSE=0
#DEBUG=0

#
# Functions
#

print_usage () {
  printf "Usage: %s [OPTION]... PROGRAM [ARG]...\n" "$(basename "$0")"
  printf "Run a program vith v4l1 compatibility library preloaded\n"
  printf "\nOPTIONS:\n"
  print_option "-v" "Verbose mode"
  print_option "-d" "Debug mode"
  print_option "-h" "Print this help message"
  printf "\nPROGRAM:\n"
  printf "Any ELF binary to run with v4l1 compatibility library preloaded.\n"
  printf "\nARGS:\n"
  printf "Any argument to path to PROGRAM.\n"
}


#
# Config files
#

[ -e "$SYSTEM_CONFIG_FILE" ] && . "$SYSTEM_CONFIG_FILE"
[ -e "$USER_CONFIG_FILE" ] && . "$USER_CONFIG_FILE"


#
# Options processing
#

while getopts "vdh" OPTION ; do
  case $OPTION in
    v) enable_verbose ;;
    d) enable_debug ;;
    h) print_usage ; exit 0 ;;
    *) print_usage ; exit 1 ;;
  esac
done ; shift $((OPTIND-1))


#
# Checks
#

# Need at least one argument
[ $# -lt 1 ] && die "Please provide at least one argument"

# This script needs file
which file > /dev/null || die "Please install file"

# The binary to run
BINARY="$1" ; shift
print_debug "BINARY=$BINARY" "ARGS=$@"

# Is it in PATH ?
BINARY_PATH="$(which "$BINARY")"
print_debug "BINARY_PATH=$BINARY_PATH"

# Argument must be a program
[ -z "$BINARY_PATH" ] && die "Can't find program $BINARY in \$PATH"


#
# MAIN
#

# Determine binary type
BINARY_TYPE="$(file -L "$BINARY_PATH")"

# Run the binary with matching architecture v4l1 library preloaded
if echo "$BINARY_TYPE" | grep -q "ELF 32-bit LSB" ; then
  print_verbose "$BINARY_PATH is an ELF 32-bit executable"
  LD_PRELOAD=/usr/lib/i386-linux-gnu/libv4l/v4l1compat.so "$BINARY_PATH" "$@"
elif echo "$BINARY_TYPE" | grep -q "ELF 64-bit LSB" ; then
  print_verbose "$BINARY_PATH is an ELF 64-bit executable"
  LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libv4l/v4l1compat.so "$BINARY_PATH" "$@"
else
  die "$BINARY_PATH is not an ELF executable"
fi
