#!/usr/bin/env bash

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

# shellcheck source=lib/package.sh
source "$MODULE_SAMBA_SHARE_PROJECT_ROOT/lib/package.sh"
# shellcheck source=lib/system.sh
source "$MODULE_SAMBA_SHARE_PROJECT_ROOT/lib/system.sh"
# shellcheck source=modules/network/samba-share/config.sh
source "$MODULE_SAMBA_SHARE_DIR/config.sh"
# shellcheck source=modules/network/samba-share/metadata.conf
source "$MODULE_SAMBA_SHARE_DIR/metadata.conf"

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

module_samba_share_config_path() {
  printf '%s/%s\n' "$MODULE_SAMBA_SHARE_PROJECT_ROOT" "$POSTINSTALL_SAMBA_SHARES_FILE"
}

module_samba_share_global_settings() {
  local config_path=""
  local workgroup="WORKGROUP"
  local wsdd2_enabled="yes"

  config_path="$(module_samba_share_config_path)"
  if [[ -f "$config_path" ]]; then
    while IFS='=' read -r key value; do
      case "$key" in
        workgroup) workgroup="$value" ;;
        wsdd2) wsdd2_enabled="$value" ;;
      esac
    done < <(
      awk '
        /^[[:space:]]*workgroup:/ { print "workgroup=" $2 }
        /^[[:space:]]*wsdd2:/ { print "wsdd2=" $2 }
      ' "$config_path"
    )
  fi

  printf '%s|%s\n' "$workgroup" "$wsdd2_enabled"
}

module_samba_share_entries() {
  local config_path=""
  config_path="$(module_samba_share_config_path)"

  awk '
    function flush() {
      if (id != "") {
        print id "|" name "|" path "|" user "|" read_only "|" public "|" description
      }
    }
    /^[[:space:]]*-[[:space:]]id:/ {
      flush()
      id=$0; sub(/.*id:[[:space:]]*/, "", id)
      name=path=user=read_only=public=description=""
      next
    }
    /^[[:space:]]*name:/ { name=$0; sub(/.*name:[[:space:]]*/, "", name); next }
    /^[[:space:]]*path:/ { path=$0; sub(/.*path:[[:space:]]*/, "", path); next }
    /^[[:space:]]*user:/ { user=$0; sub(/.*user:[[:space:]]*/, "", user); next }
    /^[[:space:]]*read_only:/ { read_only=$0; sub(/.*read_only:[[:space:]]*/, "", read_only); next }
    /^[[:space:]]*public:/ { public=$0; sub(/.*public:[[:space:]]*/, "", public); next }
    /^[[:space:]]*description:/ { description=$0; sub(/.*description:[[:space:]]*/, "", description); next }
    END { flush() }
  ' "$config_path"
}

module_samba_share_ensure_include() {
  mkdir -p /etc/samba/smb.conf.d
  if ! grep -Fq 'include = /etc/samba/smb.conf.d/postinstall-home.conf' /etc/samba/smb.conf; then
    printf '\ninclude = /etc/samba/smb.conf.d/postinstall-home.conf\n' >> /etc/samba/smb.conf
  fi
}

module_samba_share_manage_wsdd2() {
  local wsdd2_enabled="$1"

  if [[ "$wsdd2_enabled" == "yes" ]]; then
    if package_install wsdd2; then
      systemctl enable --now wsdd2 || ui_warn "Impossible d'activer wsdd2"
    else
      ui_warn "Paquet wsdd2 indisponible ou installation echouee"
    fi
  fi
}

module_samba_share_render_block() {
  local share_name="$1"
  local share_path="$2"
  local share_user="$3"
  local read_only="$4"
  local is_public="$5"

  cat <<EOF
[$share_name]
   path = $share_path
   browseable = yes
   read only = $read_only
   guest ok = $is_public
   public = $is_public
   force user = $share_user
   create mask = 0644
   directory mask = 0755
EOF
}

module_samba_share_sync_file() {
  local sync_mode="${1:-add-only}"
  local settings=""
  local workgroup=""
  local wsdd2_enabled=""
  local entry=""
  local temp_file=""
  local rendered_file=""

  settings="$(module_samba_share_global_settings)"
  IFS='|' read -r workgroup wsdd2_enabled <<< "$settings"

  mkdir -p /etc/samba/smb.conf.d
  temp_file="$(mktemp)"
  rendered_file="$(mktemp)"

  if [[ "$sync_mode" == "add-only" && -f "$POSTINSTALL_SAMBA_INCLUDE_FILE" ]]; then
    awk '
      /^# BEGIN postinstall-debian managed samba$/ { skip=1; next }
      /^# END postinstall-debian managed samba$/ { skip=0; next }
      !skip { print }
    ' "$POSTINSTALL_SAMBA_INCLUDE_FILE" > "$temp_file"
  fi

  while IFS= read -r entry; do
    [[ -n "$entry" ]] || continue
    IFS='|' read -r share_id share_name share_path share_user read_only is_public description <<< "$entry"

    if ! system_user_exists "$share_user"; then
      ui_warn "Utilisateur Samba introuvable, partage ignore : $share_user"
      continue
    fi

    mkdir -p "$share_path"
    chown "$share_user:$share_user" "$share_path"
    module_samba_share_render_block "$share_name" "$share_path" "$share_user" "$read_only" "$is_public" >> "$rendered_file"
    printf '\n' >> "$rendered_file"
  done < <(module_samba_share_entries)

  {
    cat "$temp_file"
    printf '# BEGIN postinstall-debian managed samba\n'
    printf '[global]\n'
    printf '   workgroup = %s\n' "$workgroup"
    printf '   map to guest = Bad User\n'
    printf '   server min protocol = SMB2\n\n'
    cat "$rendered_file"
    printf '# END postinstall-debian managed samba\n'
  } > "$POSTINSTALL_SAMBA_INCLUDE_FILE"

  module_samba_share_manage_wsdd2 "$wsdd2_enabled"
  rm -f "$temp_file" "$rendered_file"
}

module_samba_share_install() {
  local sync_mode="${1:-add-only}"

  package_refresh_indexes
  package_install samba
  module_samba_share_ensure_include
  module_samba_share_sync_file "$sync_mode"

  testparm -s >/dev/null || return 1
  systemctl enable --now smbd
  systemctl restart smbd

  log_info "Partages Samba synchronises depuis le repo"
  ui_success "Partages Samba configures"
}

module_samba_share_test() {
  package_is_installed samba || return 1
  test -f "$POSTINSTALL_SAMBA_INCLUDE_FILE" || return 1
  test -f "$(module_samba_share_config_path)" || return 1
  testparm -s >/dev/null 2>&1 || return 1
}
