#!/bin/sh

set -exo pipefail

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

pam_library_path() {
  case "$(uname -s)" in
  "Linux" | "SunOS")
    echo "/usr/lib/security"
    ;;
  *BSD)
    echo "/usr/lib"
    ;;
  *)
    echo "UNKNOWN OS!!!"
    return 1
    ;;
  esac
}

setup_pam_conf() {
  case "$(uname -s)" in
  "Linux" | *BSD)
    sudo cp nonstick_testharness.conf "$LINUX_BSD_CONF"
    ;;
  "SunOS")
    sudo cp /etc/pam.conf /etc/pam.conf.bak
    sed 's/^\([^#]\)/nonstick-testharness \1/' <./nonstick_testharness.conf \
      | 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
PAM_LIBRARY="$(pam_library_path)/pam_testharness.so"

cleanup() {
  sudo rm "$PAM_LIBRARY"
  cleanup_pam_conf
}

sudo cp ../target/release/libnonstick_testharness.so "$PAM_LIBRARY"
setup_pam_conf
trap cleanup EXIT
"$@" && echo "SUCCESS!!!" || echo "FAILURE: $?"