#!/bin/sh -e
#
# # DASHT-DOCSETS-EXTRACT 1       2020-05-16                            2.4.0
#
# ## NAME
#
# dasht-docsets-extract - extracts [Dash] docset archives (`*.tgz` files)
#
# ## SYNOPSIS
#
# `dasht-docsets-extract` *FILE*...
#
# ### Examples
#
# `dasht-docsets-extract` NET\_Framework.tgz
#   Extracts the [Dash] docset archive file named "NET\_Framework.tgz" that is
#   located in the current working directory.
#
# `dasht-docsets-extract` NET\_Framework.tgz Font\_Awesome.tgz
#   Extracts the [Dash] docset archive files named "NET\_Framework.tgz" and
#   "Font\_Awesome.tgz" that are located in the current working directory.
#
# `dasht-docsets-extract` ../some\_path\_here/NET\_Framework.tgz
#   Extracts the [Dash] docset archive file named "NET\_Framework.tgz" that is
#   located in a subdirectory one level above the current working directory.
#
# ## DESCRIPTION
#
# Extracts the given [Dash] docset archive *FILE*s (`*.tgz` files) into the
# location specified by the `DASHT_DOCSETS_DIR` environment variable and then
# renames their extracted directories to match their rootnames (sans `.tgz`).
#
# If an extracted directory already exists, its contents are updated in place.
#
# ## ENVIRONMENT
#
# `DASHT_DOCSETS_DIR`
#   Defines the filesystem location where your [Dash] docsets are installed.
#   If undefined, its value is assumed to be `$XDG_DATA_HOME/dasht/docsets/`
#   or, if `XDG_DATA_HOME` is undefined, `$HOME/.local/share/dasht/docsets/`.
#
# ## SEE ALSO
#
# dasht-docsets-install(1), dasht-docsets-update(1), [Dash]
#
# [Dash]: https://kapeli.com/dash
#
# ## AUTHOR
#
# Written in 2016 by Suraj N. Kurapati <https://github.com/sunaku/dasht>
# Distributed under the terms of the ISC license (see the LICENSE file).

: ${DASHT_DOCSETS_DIR:=${XDG_DATA_HOME:-$HOME/.local/share}/dasht/docsets}

test $# -gt 0
for tgz; do
  want="$DASHT_DOCSETS_DIR/$(basename "$tgz" .tgz).docset"
  have="$DASHT_DOCSETS_DIR/$(tar -t -f "$tgz" -z | head -1 | sed 's|/.*||')"

  # for dasht-docsets-update(1), the extracted directory will already exist
  # with the correct name, but we need to temporarily rename it back to the
  # wrong name so that the archive extraction below can update its contents
  # in place, rather than extracting out to a new (and different) directory
  test "$have" = "$want" -o ! -e "$want" || mv "$want" "$have"

  # extract the archive; the extracted directory's path is defined by $have
  tar -v -C "$DASHT_DOCSETS_DIR" -x -f "$tgz" -z

  # rename the extracted directory to have the same rootname as the archive
  test "$have" = "$want" || mv "$have" "$want"

  # remove any stale files that were left behind by the previous extraction
  { find "$want" -print
    tar -t -f "$tgz" -z | sed -e "s|^[^/]*|$want|" -e 's|/$||'
  } | sort -r | uniq -c | sed -n 's/^ *1 //p' | while read -r arg; do
      if test -d "$arg"
      then rmdir "$arg"
      else rm -v "$arg"
      fi
  done
done
