# vim:set ai et sts=2 sw=2 tw=0:

SOURCE_VERSION=@SOURCE_VERSION@
OFFICIAL_BUILD=@OFFICIAL_BUILD@

message () {
  # pretty-print messages of arbitrary length
  echo "$*" | fold -s -w ${COLUMNS:-80} >&2;
}

message_nonl () {
  # pretty-print messages of arbitrary length (no trailing newline)
  echo -n "$*" | fold -s -w ${COLUMNS:-80} >&2;
}

errormsg () {
  # exit script with error
  message "$*"
  exit 1;
}

internal_errormsg() {
  # exit script with error; essentially a "THIS SHOULD NEVER HAPPEN" message
  message "$*"
  if [ -n "$OFFICIAL_BUILD" ]; then
    message "Please report the package name, version, and the text of the" \
            "above error message(s) to the Debian Bug Tracking System. " \
            "Visit <http://www.debian.org/Bugs/Reporting> on the World Wide" \
            "Web for instructions, or read the file" \
            "/usr/share/doc/debian/bug-reporting.txt (from the doc-debian" \
            "package."
  fi
  exit 1;
}

maplink () {
  # returns what symlink should point to; i.e., what the "sane" answer is
  # Keep this in sync with the debian/*.links files.
  # This is only needed for symlinks to directories.
  case "$1" in
    /etc/X11/xkb/compiled) echo /var/lib/xkb ;;
    /etc/X11/xkb/xkbcomp) echo /usr/X11R6/bin/xkbcomp ;;
    /usr/X11R6/lib/X11/app-defaults) echo /etc/X11/app-defaults ;;
    /usr/X11R6/lib/X11/fs) echo /etc/X11/fs ;;
    /usr/X11R6/lib/X11/lbxproxy) echo /etc/X11/lbxproxy ;;
    /usr/X11R6/lib/X11/proxymngr) echo /etc/X11/proxymngr ;;
    /usr/X11R6/lib/X11/rstart) echo /etc/X11/rstart ;;
    /usr/X11R6/lib/X11/twm) echo /etc/X11/twm ;;
    /usr/X11R6/lib/X11/xdm) echo /etc/X11/xdm ;;
    /usr/X11R6/lib/X11/xinit) echo /etc/X11/xinit ;;
    /usr/X11R6/lib/X11/xkb) echo /etc/X11/xkb ;;
    /usr/X11R6/lib/X11/xserver) echo /etc/X11/xserver ;;
    /usr/X11R6/lib/X11/xsm) echo /etc/X11/xsm ;;
    /usr/bin/X11) echo ../X11R6/bin ;;
    /usr/bin/rstartd) echo ../X11R6/bin/rstartd ;;
    /usr/include/X11) echo ../X11R6/include/X11 ;;
    /usr/lib/X11) echo ../X11R6/lib/X11 ;;
    *) internal_errormsg "ERROR: maplink() called with unknown path \"$1\"" ;;
  esac;
}

analyze_path () {
  # given a supplied set of pathnames, break each one up by directory and do an
  # ls -dl on each component, cumulatively; i.e.
  # analyze_path /usr/X11R6/bin -> ls -dl /usr /usr/X11R6 /usrX11R6/bin
  # Thanks to Randolph Chung for this clever hack.
  while [ -n "$1" ]; do
    G=
    message "Analyzing $1:"
    for F in $(echo "$1" | tr / \  ); do
      if [ -e /$G$F ]; then
        ls -dl /$G$F /$G$F.dpkg-* 2> /dev/null || true
        G=$G$F/
      else
        message "/$G$F: nonexistent; directory contents of /$G:"
        ls -l /$G
        break
      fi
    done
    shift
  done;
}

find_culprits () {
  message "Searching for overlapping packages..."
  DPKG_INFO_DIR=/var/lib/dpkg/info
  if [ -d $DPKG_INFO_DIR ]; then
    if [ "$(echo $DPKG_INFO_DIR/*.list)" != "$DPKG_INFO_DIR/*.list" ]; then
      POSSIBLE_CULPRITS=$(ls -1 $DPKG_INFO_DIR/*.list | egrep -v \
        "(xbase-clients|xfree86-common|xfs|xlibs)")
      SMOKING_GUNS=$(grep -l "$1" $POSSIBLE_CULPRITS)
      if [ -n "$SMOKING_GUNS" ]; then
        BAD_PACKAGES=$(printf "\\n")
        for F in $SMOKING_GUNS; do
          # too bad you can't nest parameter expansion voodoo
          P=${F%*.list}      # strip off the trailing ".list"
          PACKAGE=${P##*/}   # strip off the directories
          BAD_PACKAGES=$(printf "%s\n%s" "$BAD_PACKAGES" "$PACKAGE")
        done
        message "The following packages appear to have file overlaps" \
                "with the XFree86 packages; these packages are either very" \
                "old, or in violation of Debian Policy.  Try upgrading each of" \
                "these packages to the latest available version if possible:" \
                "for example, with the command \"apt-get install\".  If no" \
                "newer version of a package is available, you will have to" \
                "remove it: for example, with the command \"apt-get remove\". " \
                "If even the latest available version of the package has this" \
                "file overlap, please file a bug against that package with the" \
                "Debian Bug Tracking System.  You may want to refer the package" \
                "maintainer to section 12.8 of the Debian Policy manual."
        message "The overlapping packages are: $BAD_PACKAGES"
      else
        message "no overlaps found."
      fi
    else
      message "cannot search; no matches for $DPKG_INFO_DIR/*.list."
    fi
  else
    message "cannot search; $DPKG_INFO_DIR does not exist."
  fi;
}

# we require a readlink command or shell function
if ! which readlink > /dev/null 2>&1; then
  message "The readlink command was not found.  Please install version" \
          "1.13.1 or later of the debianutils package."
  readlink () {
    # returns what symlink in $1 actually points to
    perl -e '$l = shift; exit 1 unless -l $l; $r = readlink $l; exit 1 unless $r; print "$r\n"' $1;
  }
fi

check_symlinks_and_warn () {
  # for each argument, checks for symlink sanity, and warns if they aren't sane
  # should be called from preinst scripts only
  if [ -n "$*" ]; then
    for SYMLINK in $*; do
      if [ -L $SYMLINK ]; then
        if [ "$(maplink $SYMLINK)" != "$(readlink $SYMLINK)" ]; then
          message "Warning: $SYMLINK symbolic link points to the wrong" \
                  "place.  Removing."
          rm $SYMLINK
        fi
      elif [ -e $SYMLINK ]; then
        ERRMSG="ERROR: $SYMLINK exists and is not a symbolic link.  "
        ERRMSG="${ERRMSG}This package cannot be installed until this"
        if [ -f $SYMLINK ]; then
          ERRMSG="$ERRMSG file"
        elif [ -d $SYMLINK ]; then
          ERRMSG="$ERRMSG directory"
        else
          ERRMSG="$ERRMSG thing"
        fi
        ERRMSG="$ERRMSG is removed."
        message "$ERRMSG"
        errormsg "Aborting installation of $THIS_PACKAGE package."
      fi
    done
  else
    internal_errormsg "Argh.  Some chucklehead called" \
                      "check_symlinks_and_warn() with no arguments."
  fi;
}

check_symlinks_and_bomb () {
  # for each argument, checks for symlink sanity, and bombs if they aren't sane
  # should be called from postinst scripts only
  if [ -n "$*" ]; then
    for SYMLINK in $*; do
        analyze_path $SYMLINK $(readlink $SYMLINK)
        find_culprits $SYMLINK
#      PROBLEM=
#      if [ -L $SYMLINK ]; then
#        if [ "$(maplink $SYMLINK)" != "$(readlink $SYMLINK)" ]; then
#          PROBLEM=yes
#          internal_errormsg "ERROR: $SYMLINK symbolic link points to the " \
#                            "wrong place."
#        fi
#      elif [ -e $SYMLINK ]; then
#        PROBLEM=yes
#        internal_errormsg "ERROR: $SYMLINK is not a symbolic link."
#      else
#        PROBLEM=yes
#        internal_errormsg "ERROR: $SYMLINK symbolic link does not exist."
#      fi
#      if [ -n "$PROBLEM" ]; then
#        analyze_path $SYMLINK $(readlink $SYMLINK)
#        find_culprits $SYMLINK
#        exit 1
#      fi
    done
  else
    internal_errormsg "Argh.  Some chucklehead called" \
                      "check_symlinks_and_bomb() with no arguments."
  fi;
}

font_update () {
  # run $UPDATECMDS in $FONTDIRS
  if [ -z "$UPDATECMDS" ]; then
    internal_errormsg "ERROR: Some chucklehead called font_update() without" \
                      "setting \$UPDATECMDS."
  fi
  if [ -z "$FONTDIRS" ]; then
    internal_errormsg "ERROR: Some chucklehead called font_update() without" \
                      "setting \$FONTDIRS."
  fi
  for DIR in $FONTDIRS; do
    for CMD in $UPDATECMDS; do
      if which $CMD > /dev/null 2>&1; then
        SHORTCMD=$(basename $CMD)
        message_nonl "Running $SHORTCMD in $DIR font directory..."
        # KLUDGE
        if [ "$SHORTCMD" = "xftcache" ]; then
          DIR=/usr/X11R6/lib/X11/fonts/$DIR
        fi
        $CMD $DIR
        message "done."
      else
        message "Note: $CMD not found; not updating $DIR font directory data."
      fi
    done
  done;
}

check_symlinks_and_bomb /usr/X11R6/lib/X11/xkb \
                        /usr/X11R6/lib/X11/app-defaults
