#!/usr/bin/env bash

MODULE_NETWORK_IDENTITY_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_NETWORK_IDENTITY_PROJECT_ROOT="$(cd "$MODULE_NETWORK_IDENTITY_DIR/../../.." && pwd)"

# shellcheck source=modules/network/identity/config.sh
source "$MODULE_NETWORK_IDENTITY_DIR/config.sh"
# shellcheck source=modules/network/identity/metadata.conf
source "$MODULE_NETWORK_IDENTITY_DIR/metadata.conf"

module_identity_metadata() {
  printf '%s|%s|%s\n' "$MODULE_ID" "$MODULE_NAME" "$MODULE_DESCRIPTION"
}

module_identity_validate_hostname() {
  local host_name="$1"
  [[ "$host_name" =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{0,62}$ ]]
}

module_identity_update_hosts() {
  local host_name="$1"
  local domain_name="${2:-}"
  local fqdn="$host_name"
  local temp_file=""

  if [[ -n "$domain_name" ]]; then
    fqdn="$host_name.$domain_name"
  fi

  temp_file="$(mktemp)"
  awk '!/^127\.0\.1\.1[[:space:]]/' /etc/hosts > "$temp_file"
  printf '127.0.1.1 %s %s\n' "$fqdn" "$host_name" >> "$temp_file"
  cat "$temp_file" > /etc/hosts
  rm -f "$temp_file"
}

module_identity_install() {
  local host_name="${1:-$POSTINSTALL_NETWORK_IDENTITY_DEFAULT_HOSTNAME}"
  local domain_name="${2:-$POSTINSTALL_NETWORK_IDENTITY_DEFAULT_DOMAIN}"

  if ! module_identity_validate_hostname "$host_name"; then
    ui_error "Hostname invalide : $host_name"
    return 1
  fi

  if command -v hostnamectl >/dev/null 2>&1; then
    hostnamectl set-hostname "$host_name"
  else
    hostname "$host_name"
  fi
  printf '%s\n' "$host_name" > /etc/hostname
  module_identity_update_hosts "$host_name" "$domain_name"

  mkdir -p "$(dirname "$POSTINSTALL_NETWORK_IDENTITY_STATE_FILE")"
  {
    printf 'HOSTNAME=%s\n' "$host_name"
    printf 'DOMAIN=%s\n' "$domain_name"
  } > "$POSTINSTALL_NETWORK_IDENTITY_STATE_FILE"

  log_info "Hostname configure : $host_name"
  ui_success "Hostname configure : $host_name"
}

module_identity_test() {
  test -f "$POSTINSTALL_NETWORK_IDENTITY_STATE_FILE" || return 1
  test -s /etc/hostname || return 1
  hostnamectl >/dev/null 2>&1 || return 1
}
