#!/bin/sh

awk '
function trim(value) {
  sub(/^[[:space:]]+/, "", value)
  sub(/[[:space:]]+$/, "", value)
  return value
}

function has_item(list, item, count, parts, i) {
  count = split(list, parts, ",")
  for (i = 1; i <= count; ++i)
    if (trim(parts[i]) == item)
      return 1
  return 0
}

function remove_item(list, item, count, parts, i, result, value) {
  count = split(list, parts, ",")
  result = ""

  for (i = 1; i <= count; ++i) {
    value = trim(parts[i])

    if (value == "" || value == item)
      continue

    result = result (result == "" ? "" : ",") value
  }

  return result
}

function append_item(list, item) {
  if (has_item(list, item))
    return list

  return list == "" ? item : list "," item
}

{
  lines[++line_count] = $0
  equals = index($0, "=")

  if (equals > 0) {
    keys[line_count] = substr($0, 1, equals - 1)
    values[line_count] = substr($0, equals + 1)

    if (keys[line_count] == "Handled Protocols")
      handled_protocols = values[line_count]
    else if (keys[line_count] == "Mimes For krarc")
      krarc_line = line_count
    else if (keys[line_count] == "Mimes For tar")
      tar_line = line_count
  }
}

END {
  krarc_enabled = has_item(handled_protocols, "krarc")
  tar_enabled = has_item(handled_protocols, "tar")

  # Remove the temporary tlz -> krarc mapping used by an earlier
  # version of the Lzip implementation.
  if (krarc_enabled && krarc_line)
    values[krarc_line] = remove_item(values[krarc_line], "application/x-tlz")

  lzip_mapped = 0
  tlz_mapped = 0

  # Preserve user-defined protocol mappings.
  for (i = 1; i <= line_count; ++i) {
    if (keys[i] ~ /^Mimes For /) {
      if (has_item(values[i], "application/x-lzip"))
        lzip_mapped = 1

      if (has_item(values[i], "application/x-tlz"))
        tlz_mapped = 1
    }
  }

  if (krarc_enabled && !lzip_mapped) {
    if (krarc_line)
      values[krarc_line] = append_item(values[krarc_line], "application/x-lzip")
    else {
      ++line_count
      keys[line_count] = "Mimes For krarc"
      values[line_count] = "application/x-lzip"
    }
  }

  if (tar_enabled && !tlz_mapped) {
    if (tar_line)
      values[tar_line] = append_item(values[tar_line], "application/x-tlz")
    else {
      ++line_count
      keys[line_count] = "Mimes For tar"
      values[line_count] = "application/x-tlz"
    }
  }

  for (i = 1; i <= line_count; ++i) {
    if (keys[i] != "")
      print keys[i] "=" values[i]
    else
      print lines[i]
  }
}
'
