#!/bin/sh

case $- in
  *i*)
    ;;
  *)
    set -eu
    ;;
esac

first_banner=
banner() {
  if [ "$first_banner" = "$pkg" ]; then
    echo
  fi
  first_banner="$pkg"
  echo "$@" | sed -e 's/./—/g'
  echo "$@"
  echo "$@" | sed -e 's/./—/g'
  echo
}

indent() {
  sed -e 's/^/    /'
}

autopkgtest_dir_for_package() {
  local pkg="$1"
  pkg_dir=$(echo "$pkg" | sed -e 's/\(\(lib\)\?.\).*/\1\/&/')
  echo "${debci_autopkgtest_dir}/${pkg_dir}"
}

autopkgtest_incoming_dir_for_package() {
  local pkg="$1"
  pkg_dir=$(echo "$pkg" | sed -e 's/\(\(lib\)\?.\).*/\1\/&/')
  echo "${debci_autopkgtest_incoming_dir}/${pkg_dir}"
}

status_dir_for_package() {
  local pkg="$1"
  pkg_dir=$(echo "$pkg" | sed -e 's/\(\(lib\)\?.\).*/\1\/&/')
  echo "${debci_packages_dir}/${pkg_dir}"
}


log() {
  if [ "$debci_quiet" = 'false' ]; then
    echo "$@"
  fi
}

log_error() {
  echo "$@"
}


seconds_to_human_time() {
  local seconds="$1"
  local hours=$(( $seconds / 3600 ))
  local minutes=$(( ($seconds % 3600) / 60 ))
  local seconds=$(( $seconds - ($hours * 3600) - ($minutes * 60) ))
  local human_time="${hours}h ${minutes}m ${seconds}s"

  echo "$human_time"
}


command_available() {
  which "$1" >/dev/null 2>/dev/null
}

# Makes sure $lockfile exists, and is owned by the debci user
ensure_lockfile() {
  local lockfile="$1"
  if [ ! -f "$lockfile" ]; then
    touch "$lockfile"
    chown $debci_user:$debci_group "$lockfile"
  fi
}

run_with_lock_or_exit() {
  local lockfile="$1"
  ensure_lockfile "$lockfile"
  shift
  (
    flock --nonblock 9 || exit 0
    "$@"
  ) 9> "$lockfile"
}

run_with_shared_lock() {
  local lockfile="$1"
  shift
  ensure_lockfile "$lockfile"
  (
    flock --shared 9
    "$@"
  ) 9> "$lockfile"
}

run_with_exclusive_lock() {
  local lockfile="$1"
  shift
  ensure_lockfile "$lockfile"
  (
    flock --exclusive 9
    "$@"
  ) 9> "$lockfile"
}

maybe_with_proxy() {
  if command -v auto-apt-proxy >/dev/null; then
    export http_proxy=$(auto-apt-proxy 2>/dev/null || true)
  fi
  "$@"
}
