FORCED_MODE="false"

# PARSER - well, sort of
if [ "$1" = "--force" ] || [ "$1" = "-f" ]; then
  FORCED_MODE="true"
fi

check_x() {
  xdpyinfo 2>/dev/null >/dev/null
  if [ "$#" -ne 0 ]; then
    HAS_X=false
  else
    HAS_X=true
  fi
}

exit_on_error() {
  if [ "$1" != "0" ]; then
    if [ "$2" != "" ]; then
      echo "$2"
      echo "return value: $1"
      exit "$1"
    else
      echo "Failure"
      echo "return value: $1"
      exit "$1"
    fi
  fi
}

source_file() {
  if [ ! -f "$1" ]; then
    exit_on_error "1" "Failed reading (sourcing) file: $1"
  fi
  # shellcheck disable=SC1090
  . "$1"
}

get_date() {
  # shellcheck disable=SC2312
  printf '%s' "$(date '+%Y-%m-%d %H:%M:%S')"
}

log() {
  printf '%s' "["
  get_date
  echo "] $*"
}

log_to_file() {
  if [ "${LOG_FILE-}" != "" ]; then
    log "$*" >>"${LOG_FILE}"
  fi
}

do_exec() {
  CMD="$1"
  ERR_MSG="$2"
  log "${CMD}"
  "${CMD}"
  exit_on_error "$?" "${ERR_MSG}"
  log "${CMD}: OK"
}

# shellcheck disable=SC2329
debug() {
  if [ -n "${DEBUG}" ]; then
    echo "$*"
  fi
}

ask_question() {
  Q=$1

  RET=1

  if [ "${FORCED_MODE}" = "true" ]; then
    # RET=0 means yes
    RET=0
  elif [ "${HAS_X}" = "true" ]; then
    zenity --question --text "${Q}"
    RET=$?
  else
    echo "${Q} [Y/n]"
    read -r ANSWER
    if [ "${ANSWER}" = "Y" ] || [ "${ANSWER}" = "y" ]; then
      RET=0
    fi
  fi
  return "${RET}"
}

###
# LOGGING

# XXX what if the message starts with a minus??
debug() {
  if test "${debug-}"; then
    echo "$*" 1>&2
    if test "${logfile-}"; then
      echo "$*" >>"${logfile}"
    fi
  fi
  if test "${syslog-}"; then
    # shellcheck disable=SC2312
    logger -t "$(get_script_name)" -p user.debug "$*"
  fi
}

# XXX what if the message starts with a minus??
error() {
  echo "$*" 1>&2
  if test "${logfile}"; then
    echo "$*" >>"${logfile}"
  fi
  if test "${syslog}"; then
    # shellcheck disable=SC2312
    logger -t "$(get_script_name)" -p user.err "$*"
  fi
  if test "${sms-}"; then
    echo "$*" | sendsms "${phone-}"
  fi
}

# XXX what if the message starts with a minus??
info() {
  if test ! "${quiet-}"; then
    echo "$*" 1>&2
  fi
  if test "${logfile}"; then
    echo "$*" >>"${logfile}"
  fi
  if test "${syslog}"; then
    # shellcheck disable=SC2312
    logger -t "$(get_script_name)" -p user.info "$*"
  fi
}

# XXX what if the message starts with a minus??
notice() {
  echo "$*" 1>&2
  if test "${logfile}"; then
    echo "$*" >>"${logfile}"
  fi
  if test "${syslog}"; then
    # shellcheck disable=SC2312
    logger -t "$(get_script_name)" -p user.notice "$*"
  fi
  if test "${sms}"; then
    echo "$*" | sendsms "${phone}"
  fi
}

# XXX what if the message starts with a minus??
warn() {
  echo "$*" 1>&2
  if test "${logfile}"; then
    echo "$*" >>"${logfile}"
  fi
  if test "${syslog}"; then
    # shellcheck disable=SC2312
    logger -t "$(get_script_name)" -p user.warning "$*"
  fi
}

###
# RUNNING PROGRAMS

run() {
  if test "${simulate-}"; then
    info "Would run $*"
  else
    debug "Running $*"
    if test "${logfile}"; then
      #"$@" 2>&1 | tee -a "${logfile}"
      2>&1 "$@" 2>&1 | tee -a "${logfile}"
    else
      "$@"
    fi
  fi
}

silent() {
  "$@" >/dev/null 2>/dev/null
}

###
# FILE MANIPULATION

# Return the directory part of a path.
get_directory_part() {
  location=$(get_location_part "$1")
  dir="${location%/*}"

  echo "${dir}"
  return 0
}

# Get the amount of disk space used by a file or directory.
#
# Usage: get_size_of_file_or_directory <mount point or file>
# Returns: disk usage in kilobytes
get_size_of_file_or_directory() {
  file="$1"
  size=$(du -ks "${file}" | cut -f 1)
  if test $? -ne 0; then
    error "Cannot determine disk usage of ${file}"
    return 1
  fi
  debug "${file} uses ${size} kilobytes of disk space"
  echo "${size}"
  return 0
}

# Return the filename part of a path.
get_filename_part() {
  location=$(get_location_part "$1")
  echo "${location##/*/}"
  return 0
}

# Return the hostname from a remote path.
#
# Usage: get_hostname_part <hostname:/path/to/file>
# Returns: hostname
get_hostname_part() {
  echo "$1" | cut -f 1 -d :
}

# Return the local part of a path
# get_location_part hostname:/path/to/file -> /path/to/file
get_location_part() {
  echo "$1" | cut -f 2 -d :
}

# Return the path to the user's temporary directory.
get_temporary_directory() {
  if test "${TMPDIR}"; then
    if test -d "${TMPDIR}"; then
      echo "${TMPDIR}"
      return 0
    else
      debug "${TMPDIR} does not exist, creating"
      mkdir "${TMPDIR}"
      if test $? -eq 0; then
        echo "${TMPDIR}"
        return 0
      else
        error "Cannot create ${TMPDIR}, falling back to /tmp"
        if test -d /tmp; then
          if test -w /tmp; then
            TMPDIR=
            echo "/tmp"
            return 0
          else
            error "/tmp is not writeable"
            return 1
          fi
        else
          error "/tmp does not exist"
          return 1
        fi
      fi
    fi
  elif test -d "${HOME}/tmp"; then
    if test -w "${HOME}/tmp"; then
      echo "${HOME}/tmp"
      return 0
    else
      debug "${HOME}/tmp is not writeable, falling back to /tmp"
      if test -d /tmp; then
        if test -w /tmp; then
          echo "/tmp"
          return 0
        else
          error "/tmp is not writeable"
          return 1
        fi
      else
        error "/tmp does not exist"
        return 1
      fi
    fi
  elif test -d /tmp; then
    if test -w /tmp; then
      echo "/tmp"
      return 0
    else
      error "/tmp is not writeable"
      return 1
    fi
  else
    error "/tmp does not exist"
    return 1
  fi
}

# whether a path is on a locally mounted file system or a remote SSH server
is_remote() {
  echo "$1" | grep -q ":"
}

# add a line of text to the start of a file
prepend() {
  line=$1

  file=$2
  if test ! -f "${file}"; then
    error "Cannot access ${file}"
    return 1
  fi

  tempfile="${file}.$$.temp"
  if test -f "${tempfile}"; then
    error "${tempfile} already exists"
    return 1
  fi

  echo "${line}" >"${tempfile}"

  if test "${status-}" -ne 0; then
    error "Cannot store line in ${tempfile}"
    rm "${tempfile}"
    return 1
  fi

  mergefile="${file}.$$.merge"
  if test -f "${mergefile}"; then
    error "${mergefile} already exists"
    return 1
  fi

  cat "${tempfile}" "${file}" >"${mergefile}"
  mv "${file}" "${file}.bak"
  mv "${mergefile}" "${file}"
}

# add a line of text to the end of a file
append() {
  line=$1

  file=$2
  if test ! -f "${file}"; then
    error "Cannot access ${file}"
    return 1
  fi

  echo "${line}" >>"${file}"
}

###
# NETWORKING

get_address_helper() {
  host="$1"
  nameserver="$2"
  tmpfile="${tmpdir:-/tmp}/get_address_helper$$"
  tries=3

  debug "Resolving ${host} using ${nameserver:-default nameservers}"
  while test "${tries}" -gt 0; do
    host "${host}" "${nameserver}" >"${tmpfile}"
    if test $? -eq 0; then
      # read lines of the form
      # endbracket.net          A       203.214.81.131
      # shellcheck disable=SC2094
      while read -r host type address; do
        if test "${type}" = "A"; then
          echo "${address}"
          # shellcheck disable=SC2094
          rm "${tmpfile}"
          return 0
        fi
      done <"${tmpfile}"
    fi
    tries=$((tries - 1))
  done
  error "Cannot resolve ${host} using ${nameserver}"
  rm "${tmpfile}"
  return 1
}

# get_address_of <hostname>
# Determine's the current IP address of a host.
get_address_of() {
  host="$1"

  # nameservers should be set elsewhere, e.g. in ~/.checkdns
  if test -n "${nameservers-}"; then
    debug "Getting address of ${host} using ${nameservers}"
    for nameserver in ${nameservers}; do
      address=$(get_address_helper "${host}" "${nameserver}")
      if test $? -eq 0; then
        debug "Address of ${host} is ${address}"
        echo "${address}"
        return 0
      fi
    done
  else
    debug "Getting address of ${host} using default nameservers"
    address=$(get_address_helper "${host}")
    if test $? -eq 0; then
      debug "Address of ${host} is ${address}"
      echo "${address}"
      return 0
    fi
  fi

  error "Cannot get address of ${host}"
  return 1
}

# Determine whether a host is up
host_up() {
  host="$1"
  ping -c 3 "${host}" >/dev/null
}

# XXX This doesn't test if the interface is up, only if it's configured
interface_up() {
  _status=
  _interface="$1"
  _temp="$(get_temporary_directory)/network_up.$$"
  i=0

  netstat -i >"${_temp}"
  cat "${_temp}"
  if test $? -eq 0; then
    i=0
    # shellcheck disable=SC2034
    while read -r Iface MTU Met RXOK RXERR RXDRP RXOVR TXOK TXERR TXDRP TXOVR Flg; do
      i=$((i + 1))

      if test "${i}" -eq 1; then
        continue
      fi

      if test -z "${Flg}"; then
        echo "Iface is ${Iface}"
        info "netstat output does not contain Flg field, assuming unsupported operating system"
        break
      fi
      if test "${Iface}" = "${_interface}"; then
        if test "${Flg/U/}" != "${Flg}"; then
          _status=up
        else
          _status=down
        fi
        debug "${_interface} is ${_status}"
        break
      fi
    done <"${_temp}"
  else
    warning "Cannot run netstat -i, falling back to less reliable ifconfig test"
  fi
  rm "${_temp}"

  if test -z "${_status}"; then
    ifconfig "${interface-}" >/dev/null # discard stdout, keep stderr
    if test $? -eq 0; then
      info "${_interface} is configured, assuming this means it's up"
      _status=up
    else
      info "Cannot get status of ${_interface}, assuming this means it's down"
      _status=down
    fi
  fi

  if test "${_status}" = "up"; then
    return 0
  else
    return 1
  fi
}

# whether we can get to the internet at the moment
internet_reachable() {
  silent ping -c 3 mullvad.net
}

###
# MISCELLANEOUS
# Return the name of the script that called this function.
# get_script_name
get_script_name() {
  echo "${0##/*/}"
}

###
# STRING PROCESSING

# break <string> into words by splitting on delimiter <delim>
# Usage: split <delim> <string>
# Example: split , "foo,bar,baz"
split() {
  if test "$#" -ne 2; then
    echo "Usage: split <delim> <string>" 1>&2
    return 1
  fi

  delim="$1"
  shift
  IFS="${delim}"
  for word in $1; do
    echo "${word}"
  done
}
