#!/bin/bash

###########################################################
## Copyright (c) 2002-2025 Alexey Kuryakin daqgroup@mail.ru
###########################################################

###########################################################
## MIME type definitions for DaqGroup.
###########################################################

###########################################################
source $(crwkit which crwlib_base.sh); # Use base library #
source $(crwkit which crwlib_file.sh); # Use file library #
###########################################################

function version(){
 echo "$scriptname version 1.0";
};

function print_help(){
 version;
 echo "Copyright (c) 2002-2025 Alexey Kuryakin daqgroup@mail.ru";
 echo "Utility to print mime.type file for DaqGroup.";
 echo "Usage: $scriptname [options]";
 echo "Options:";
 echo " --version    - print version";
 echo " -h,--help    - print help screen";
 echo " -p,--path    - print mime file path";
 echo " -c,--cat     - cat mime file content";
 echo " -q,--query   - query (cat) mime types in ~/.mime.type";
 echo " -s,--setup   - mime setup, i.e. write to ~/.mime.type";
};

function markdownviewer_mime(){
 local mv="$(unix which markdownviewer)";
 if [ -z "$mv" ]; then return 1; fi;
 mv="$(realpath "$mv")";
 if [ ! -e "$mv" ]; then return 1; fi;
 local mime="$(dirname "$mv")/$(basename "$mv" .sh).mime";
 if [ -e "$mime" ]; then echo "$mime"; fi;
};

function daqgroup_mime(){
 local mime="$(markdownviewer_mime)";
 if [ -z "$mime" ] || [ ! -e "$mime" ]; then mime="$scriptHOME/daqgroup.mime"; fi;
 if [ -n "$mime" ]; then echo "$mime"; fi;
};

function path_mime(){
 if [ -e "$1" ]; then
  echo "$1";
 else
  fatal 1 "Error: could not find mime file.";
 fi;
};

function cat_mime(){
 if [ -e "$1" ]; then
  cat "$1";
 else
  fatal 1 "Error: could not find mime file.";
 fi;
};

function query_mime(){
 if [ -e "$1" ]; then
  cat "$1";
 else
  fatal 1 "Error: could not find \"$1\".";
 fi;
};

function setup_mime(){
 if [ -e "$1" ] && [ -n "$2" ]; then
  cat "$1" | tee $2;
 else
  fatal 1 "Error: could not find \"$1\".";
 fi;
};

function main(){
 local mime="$(daqgroup_mime)";
 case $1 in
  --version)          version; ;;
  -h|-help|--help)    print_help; ;;
  -p|-path|--path)    path_mime "$mime"; ;;
  -c|-cat|--cat)      cat_mime "$mime"; ;;
  -q|-query|--query)  query_mime $HOME/.mime.types; ;;
  -s|-setup|--setup)  setup_mime "$mime" $HOME/.mime.types; ;;
  *)                  fatal 1 "Usage: $scriptname --version|-h|--help|-p|--path|-c|--cat|-q|--query|-s|--setup"; ;;
 esac;
};

main "$@";

#############
# END OF FILE
#############
