#!/bin/bash
# -*- mode: sh; sh-basic-offset: 2; indent-tabs-mode: nil; -*-
# vim:set ft=sh et sw=2 ts=2:
#
# dhclient-mock for test scripts
#
# Set the following in your ipv6-prefix-wan-${interface}.conf file to test:
#
#if [ "$reason" = "BOUND6" ]; then
#  old_ip6_prefix=<ip6-prefix/len>
#  new_ip6_prefix=<ip6-prefix/len>
#  new_max_life=100
#elif [ "$reason" = "STOP6" ]; then
#  old_ip6_prefix=<ip6-prefix/len>
#fi

unset IFS

err() {
  printf >&2 "%s\n" "$*"
}

fail() {
  local -i rc=0
  [[ $1 != 0 ]] && { printf 2>/dev/null -v rc "%d" "$1" || rc=1; }
  shift
  [[ $1 ]] && { if [[ $rc == 0 ]]; then echo "$@"; else err "$@"; fi; }
  exit "$rc"
}

[[ ${DHCLIENT_MOCK_FAIL-} || ${DHCLIENT_MOCK_OUTPUT-} ]] && {
  args='' arg=''; for arg in "$@"; do args+="${args:+ }'${arg}'"; done
  fail "${DHCLIENT_MOCK_FAIL:-0}" \
       "${DHCLIENT_MOCK_OUTPUT+${DHCLIENT_MOCK_OUTPUT/@ARGS@/${args}}}"
}

SCRIPT='' PID='' CMD=''

parse_args() {
  local arg nextarg=''

  for arg in "$@"; do

    [[ ${nextarg} ]] && {
      case ${nextarg} in
        script) SCRIPT=${arg} ;;
        pid) PID=${arg} ;;
      esac
      nextarg=''
      continue
    }

    case ${arg} in
      -sf) nextarg=script ;;
      -pf) nextarg=pid ;;
      *) CMD=${arg}; break ;;
    esac
  done
  return 0
}

usage() {
  err "Usage: ${0##*/} [ -sf <script> ] [ -pf <pid> ] <interface>"
  err "Usage: ${0##*/} [ -pf <pid> ] sleep"
}

parse_args "$@"

case ${CMD} in
  sleep)
    if [[ ${PID} ]]; then
      "$0" -pf "${PID}" xsleep &
    else
      "$0" xsleep &
    fi
    exit 0
    ;;
  xsleep)
    [[ $nmg_show_debug ]] && echo "Spawned background dhclient_test [$$]"
    [[ ${PID} ]] && echo $$ > "${PID}"
    sleep 5
    exit 0
    ;;
  '') usage; exit 1 ;;
esac


[[ ${SCRIPT} ]] || exit 0

export interface=${CMD}
export reason=BOUND6

[[ ${PID} ]] && echo $$ > "${PID}"

(exec "${SCRIPT}" </dev/null) &
exit 0
