#!/bin/sh

set -ex

LINUX_BSD_CONF="/etc/pam.d/nonstick-testharness"

patch_pam_conf() {
  SRC="$1"
  DST="$2"
  LIB="$3"
  SUN_PATCH=""
  if [ "$(uname -s)" = "SunOS" ]; then
    SUN_PATCH="s/^#Sun#//"
  fi
  sed -e "s#pam_testharness\.so#$LIB#" -e "$SUN_PATCH" <"$SRC" >"$DST"
}

setup_pam_conf() {
  SRC="$1"
  case "$(uname -s)" in
  "Linux" | *BSD)
    # For Linux-PAM and OpenPAM, PAM is configured with the per-service files
    # in /etc/pam.d/...
    sudo cp "$SRC" "$LINUX_BSD_CONF"
    ;;
  "SunOS")
    # On SunOS, PAM has just the one configuration file,
    # with the service prepended to each line.
    sudo cp /etc/pam.conf /etc/pam.conf.bak
    sed 's/^\([^#]\)/nonstick-testharness \1/' <"$SRC" \
      | sudo tee -a /etc/pam.conf >/dev/null
    ;;
  *)
    echo "UNKNOWN OS!!!"
    return 1
    ;;
  esac
}

cleanup_pam_conf() {
  case "$(uname -s)" in
  "Linux" | *BSD)
    sudo rm "$LINUX_BSD_CONF"
    ;;
  "SunOS")
    sudo mv /etc/pam.conf.bak /etc/pam.conf
    ;;
  esac
}

HERE="$(dirname -- "$0")"
cd "$HERE"
cargo build --release

cleanup() {
  rm -r "$MY_TEMP"
  sudo rm -r "$ROOT_TEMP"
  cleanup_pam_conf
}

MY_TEMP="$(mktemp -d -t nonstick-user-XXXXXX)"
ROOT_TEMP="$(sudo mktemp -d -t nonstick-root-XXXXXX)"
sudo chmod a+rx "$ROOT_TEMP"
PAM_LIBRARY="$ROOT_TEMP/pam_nonstick.so"
sudo cp ../target/release/libnonstick_testharness.so "$PAM_LIBRARY"
patch_pam_conf ./nonstick_testharness.conf "$MY_TEMP/nonstick-testharness" "$PAM_LIBRARY"
setup_pam_conf "$MY_TEMP/nonstick-testharness"
trap cleanup EXIT
"$@" && echo "SUCCESS!!!" || echo "FAILURE: $?"