#!/bin/bash

valid_local_user() {
  [[ "$1" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]]
}

valid_utc_timestamp() {
  [[ "$1" =~ ^[0-9]{8}T[0-9]{6}Z$ ]]
}

port_state_from() {
  local status="$1"
  local output="$2"
  if (( status != 0 )); then
    printf 'error\n'
  elif [[ -n "$output" ]]; then
    printf 'open\n'
  else
    printf 'closed\n'
  fi
}

denial_state_from() {
  local status="$1"
  local output
  output="$(printf '%s' "$2" | /usr/bin/tr '[:upper:]' '[:lower:]')"
  if (( status == 0 )); then
    printf 'allowed\n'
  elif [[ "$output" == *'permission denied'* ]] &&
      { [[ "$output" == *'/var/run/docker.sock'* ]] || [[ "$output" == *'unix:///var/run/docker.sock'* ]]; }; then
    printf 'denied\n'
  else
    printf 'ambiguous\n'
  fi
}

cleanup_result_from() {
  local command_status="$1"
  local objects="$2"
  local port="$3"
  local paths="$4"
  if (( command_status == 0 )) && [[ "$objects" == none && "$port" == closed && "$paths" == none ]]; then
    printf 'clean\n'
  else
    printf 'partial\n'
  fi
}

compose_contract_self_test() {
  if ! valid_local_user 'operator-observer'; then return 1; fi
  if valid_local_user '-bad'; then return 1; fi
  if valid_local_user 'bad space'; then return 1; fi
  if ! valid_utc_timestamp '20260905T235959Z'; then return 1; fi
  if valid_utc_timestamp '20260905-235959'; then return 1; fi
  if [[ "$(port_state_from 1 'ss failed')" != error ]]; then return 1; fi
  if [[ "$(port_state_from 0 'LISTEN')" != open ]]; then return 1; fi
  if [[ "$(port_state_from 0 '')" != closed ]]; then return 1; fi
  if [[ "$(denial_state_from 0 '')" != allowed ]]; then return 1; fi
  if [[ "$(denial_state_from 1 'permission denied: /var/run/docker.sock')" != denied ]]; then return 1; fi
  if [[ "$(denial_state_from 1 'permission denied: /tmp/config')" != ambiguous ]]; then return 1; fi
  if [[ "$(denial_state_from 125 'account unavailable')" != ambiguous ]]; then return 1; fi
  if [[ "$(cleanup_result_from 0 none closed none)" != clean ]]; then return 1; fi
  if [[ "$(cleanup_result_from 0 'container:abc;' closed none)" != partial ]]; then return 1; fi
  if [[ "$(cleanup_result_from 0 none open none)" != partial ]]; then return 1; fi
  if [[ "$(cleanup_result_from 0 none closed 'release=present')" != partial ]]; then return 1; fi
  if [[ "$(cleanup_result_from 1 none closed none)" != partial ]]; then return 1; fi
}
