#!/bin/ksh
#
# $Id: try,v 1.4 2025-07-14 01:13:11-04 vogelke Exp $
#
# NAME:
#    try
#
# SYNOPSIS:
#    try [-dhqvw] [--verbose] [--enable-feature]
#       [--disable-feature] [--prefix=/dir] [files]
#
# DESCRIPTION:
#    program to ...
#
# OPTIONS:
#    -d, --debug             prints debug information.
#    -h, --help              print this message
#    -q, --quiet             do not print extra information
#    -v, --version           print the version and exit
#    -w, --where             print script location and exit.
#
#    --verbose               print extra information
#  
#    --disable-FEATURE       do not include FEATURE
#                            (same as --enable-FEATURE=no)
#    --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
#    --prefix=PREFIX         install files in PREFIX
#
#    Features:
#
#    --enable-abc            do abc (default is yes)
#    --enable-def            do def
#    --enable-xyz            do xyz
#
# EXAMPLE:
#    try --prefix=/opt --enable-def=x --disable-abc myfile
#
# AUTHOR:
#    Based on Free Software Foundation configure scripts.
#
#    Karl Vogel <vogelke+unix@pobox.com>
#    Nobody, Inc

export PATH=/bin:/usr/sbin:/usr/bin:/usr/local/bin
set -o nounset
tag=${0##*/}
umask 022
PS4='${tag}-${LINENO}: '

# ======================== FUNCTIONS =============================
# Logging: use "kill $$" to kill the script with signal 15 even if we're
# in a function, and use the trap to avoid the "terminated" message you
# normally get by using "kill".

trap 'exit 1' 15
logmsg () { echo "$(date '+%F %T') $tag: $@" >&2 ; }
warn ()   { logmsg "WARN: $@"; }
die ()    { logmsg "FATAL: $@"; kill $$ ; }

# checkvar: reject invalid shell variable names.

checkvar () {
    case "$(echo $1 | sed 's/[-a-zA-Z0-9_]//g')" in
        "") ;;
        *)  die "$1: invalid feature name" ;;
    esac
}

# usage: prints an optional string plus part of the comment
#   header (if any) to stderr, and exits with code 1.

usage () {
    (
        case "$#" in
            0)  ;;
            *)  echo "usage error: $*"; echo ;;
        esac

        awk '/^# NAME/,/^# AUTHOR/ {
             if ($2 == "AUTHOR:") exit
             print substr($0, 2)
        }' $0
    ) 1>&2

    exit 1
}

# version: prints the current version to stdout.

version () {
    awk '{split($2,a,","); n=a[1]; split($5,a,"."); v1=a[1]; v2=a[2];
          printf "%s v%d.%2.2d %s %s\n", n, v1, v2, $8, $9}' <<'    EOV'
    $RCSfile: try,v $ $Revision: 1.4 $ $Date: 2025-07-14 01:13:11-04 $
    EOV
    exit 0
}

where () {
    awk '/Host:/ {h=$2}; /Source:/ {s=$2};
         END {
             sub("/RCS", "", s); sub(",v", "", s); print "file://" h s
         }' <<'    EOW'
    \$Host: my.host.name $
    \$Source: /doc/html/htdocs/bezoar.org/local/posts/2025/0714/fsf-option-handling/RCS/try,v $
    EOW
    exit 0
}

# ======================== MAIN PROGRAM ==========================

# Defaults:
ac_help=
ac_prev=
ac_invalid="invalid option; use -h or --help to show usage"
argv=

# Initialize some variables set by options.
debug=no
enable_abc=yes
enable_def=no
enable_xyz=no
prefix=/usr/local
silent=no
verbose=no

for ac_option
do

    # If the previous option needs an argument, assign it.
    case "$ac_prev" in
        "") ;;
        *)  eval "$ac_prev=\$ac_option"; ac_prev=; continue ;;
    esac

    case "$ac_option" in
        -*=*) ac_optarg=$(echo "$ac_option" | sed 's/[-_a-zA-Z0-9]*=//') ;;
        *)    ac_optarg= ;;
    esac

    # main switch
    case "$ac_option" in
        -disable-* | --disable-*)
            ac_feature=$(echo $ac_option | sed -e 's/-*disable-//')
            checkvar "$ac_feature"
            ac_feature=$(echo $ac_feature | sed 's/-/_/g')
            eval "enable_${ac_feature}=no" ;;
    
        -enable-* | --enable-*)
            ac_feature=$(echo $ac_option |
                    sed -e 's/-*enable-//' -e 's/=.*//')
            checkvar "$ac_feature"
            ac_feature=$(echo $ac_feature | sed 's/-/_/g')
            case "$ac_option" in
                *=*) ;;
                *)   ac_optarg=yes ;;
            esac
            eval "enable_${ac_feature}='$ac_optarg'" ;;
    
        -d | -debug | --debug | --debu | --deb | --de)
            debug=yes ;;
    
        -h | -help | --help | --hel | --he)
            usage ;;
    
        -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
            ac_prev=prefix ;;
    
        -prefix=* | --prefix=* | --prefi=* |\
        --pref=* | --pre=* | --pr=* | --p=*)
            prefix="$ac_optarg" ;;
    
        -q | -quiet | --quiet | --quie | --qui | --qu | --q)
            silent=yes; verbose=no ;;
    
        -verbose | --verbose | --verbos | --verbo | --verb)
            verbose=yes; silent=no ;;
    
        -v | -version | --version | --versio | --versi | --vers)
            version; exit 0 ;;
    
        -w | -where | --where | --wher | --whe | --wh)
            where; exit 0 ;;
    
        -*) die "$ac_option: $ac_invalid" ;;

        *)  case "$argv" in
                "") argv="$ac_option" ;;
                *)  argv="$argv $ac_option" ;;
            esac ;;
    esac
done

case "$ac_prev" in
    "") ;;
    *)  die "missing arg to --$(echo $ac_prev | sed 's/_/-/g')" ;;
esac

# Debug on?
test "$debug" = "yes" && echo "DEBUG ON" && set -x

# Try creating temp files.
logmsg "testing mktemp for a directory"
tmpdir=$(mktemp -dq /tmp/$tag.XXXXXX)

case "$?" in
    0) trap "rmdir $tmpdir; exit 1" ERR ;; # ksh only
    *) die "can't create tmpdir" ;;
esac

logmsg "testing mktemp for a single file"
tmpfile=$(mktemp -q /tmp/$tag.XXXXXX)

case "$?" in
    0) trap "rm -f $tmpfile; exit 1" ERR ;; # ksh only
    *) die "can't create tmpfile" ;;
esac

cleanup () { rm -f $tmpfile; rmdir $tmpdir; }

# Test for specific features.
echo "  debug=[$debug]"
echo " prefix=[$prefix]"
echo "verbose=[$verbose]"
echo " silent=[$silent]"
echo "   argv=[$argv]"
echo
echo "Features:"

case "X${enable_abc}" in
    X | Xno) echo "abc is DISABLED" ;;
    Xyes)    echo "abc is ENABLED" ;;
    *)       echo "abc is ENABLED as $enable_abc" ;;
esac

case "X${enable_def}" in
    X | Xno) echo "def is DISABLED" ;;
    Xyes)    echo "def is ENABLED" ;;
    *)       echo "def is ENABLED as $enable_def" ;;
esac

case "X${enable_xyz}" in
    X | Xno) echo "xyz is DISABLED" ;;
    Xyes)    echo "xyz is ENABLED" ;;
    *)       echo "xyz is ENABLED as $enable_xyz" ;;
esac

# All done.
logmsg "Done"
cleanup
exit 0
