#!/bin/bash
#
# filenodemap_hexedit: Similar to relation_hexedit, but sets the
# offsets in the pg_filenode.map

usage() {
  cat <<EOM
  Usage:
  $(basename "$0") [dbname]

EOM
  exit 0
}

#[ -z "$1" ] && { usage; }

source ./hexedit.cfg

dbname=$1

if [ -z "$dbname" ]
then
    dbpath="global"
else
    dbpath=$(psql --no-psqlrc -tA -c "SELECT 'base/' || oid FROM pg_database WHERE datname = '$dbname'")
fi

# Put minimal .wxHexEditor registry style config file in place, so old tags are
# forgotten.  This is also where we generate convenience "Go to Offset" dialog
# offsets in the registry/cache (this comes from OFFSETS env var).
echo "Replacing $wxconfig with pg_hexedit optimized settings..."
cat > "$wxconfig" <<- EOM
UpdateCheck=0
FakeBlockLines=1
FakeBlockSize=8k
ColourHexBackground=#FFFFFF
ColourHexBackgroundZebra=#FFFFFF
UseBytesPerLineLimit=1
BytesPerLineLimit=$BYTES_PER_LINE_LIMIT
FontSize=$FONTSIZE
CharacterEncodingFamily=Code for Information Interchange
CharacterEncoding=ASCII - American Standard Code for Information Interchange
ScreenFullScreen=1
AutoShowTagPanel=0
GoToOptions=7
$OFFSETS
EOM

PGDATA=$(psql --no-psqlrc -tA -c "SELECT setting FROM pg_settings WHERE name = 'data_directory'")
echo "Determined that data directory is $PGDATA"

FULLPATH="$PGDATA/$dbpath/pg_filenode.map"
echo $FULLPATH

if [ -f $FULLPATH ]; then
  echo "Running pg_filenodemapdata against $FULLPATH"
  echo "Caution: Saving changes to authoritative pg_filenode.map using wxHexEditor can cause irreparable damage."
else
  echo "File $FULLPATH doesn't exist."
  exit 1  
fi

# Generate tags at a path that we know wxHexEditor will look for them:
if ! ./pg_filenodemapdata -X $FULLPATH > "$FULLPATH.tags"
then
  echo "Error encountered by pg_filenodemapdata. Could not generate all tags."
  echo "You may still wish to run: $HEXEDITOR $FULLPATH"
  exit 1
fi
  
echo "Opening $FULLPATH with $HEXEDITOR..."
# Output from wxHexEditor is verbose, and not terribly useful, so we redirect:
echo $HEXEDITOR "$FULLPATH"
$HEXEDITOR "$FULLPATH" &> /dev/null
