#!/usr/bin/bash

# Copyright (c) 2023 Timothe Litt

# ********************************************************************
# Machine generated. Contains non-printable characters - DO NOT EDIT *
# ********************************************************************

# See wxs2sh

VERSION='V1.0.0'
SELF="$(basename "$0")"

SRCDIR="opt/OpenSIMH/bin"
DSTDIR="/opt/OpenSIMH"

function displayVersion() {
    echo "$SELF $VERSION"
    exit 0
}

function displayHelp() {
    cat <<EOF
$SELF [options]

  options
    -i      - install simulators
    -r      - remove simulators
    -a      - default reply is 'all'
    -n      - default reply is 'none'
    -d path - destination root ($DSTDIR)
    -s path - source directory ($SRCDIR)
    -V      - display version
    -h      - this help

Default is to list available groups with descriptions.

-i and -r are interactive.

EOF
    exit 0
}

function die() {
    echo "Error: $*" >&2
    exit 99
}

REMOVE=
ACTION=
DEFAULT=

while getopts 'ad:inrs:hV-:' opt; do
    case $opt in
        a)
            DEFAULT="all"
            ;;
        d)
            DSTDIR="$OPTARG"
            ;;
        i)
            ACTION="install"
            ;;
        n)
            DEFAULT="none"
            ;;
        r)
            REMOVE=1
            ACTION="remove"
            ;;
       s)
            SRCDIR="$OPTARG"
            ;;
        h)
            displayHelp
            ;;
        V)
            displayVersion
            ;;
        -)
            if [ "$OPTARG" == "version" ]; then
                displayVersion
            elif [ "$OPTARG" == 'help' ]; then
                 displayHelp
            else
                echo "Unknown option -$OPTARG" >&2
                exit 1
            fi
            ;;
        *)
            echo "$SELF -h for usage" >&2
            exit 1
            ;;
    esac
done
shift $(( OPTIND - 1 ))

LMAT=$'^([0-9-]+)\x01([^\x01]*)\x01([^\x01]*)\x01(.*)$'
PAD='                                                                                '

function decode() {
    local i="$1" pfx="$2"

    [[ "${FEATURES[$i]}" =~ $LMAT ]] || die "Bad data ($i) ${FEATURES[$i]}"
    eval "${pfx}TAG=\"${BASH_REMATCH[1]}\""
    eval "${pfx}SEQ=( \$(tr \"-\" \" \" <<<\"\$${pfx}TAG\" ) )"
    eval "${pfx}TITLE=\"${BASH_REMATCH[2]}\""
    eval "${pfx}DESC=\"${BASH_REMATCH[3]}\""
    eval "${pfx}FILES=\"${BASH_REMATCH[4]}\""
    eval "${pfx}depth=\"\${#${pfx}SEQ[@]}\""
}

FEATURES=(
'1Complete packageThe Complete Open SIMH Simulator package'
'1-3Advanced ComputerPDQ-3'
'1-4AT&T3B2-400, 3B2-7003b2-400 3b2-700'
'1-5AltairAltair 8080, Z80altair altairz80'
'1-6BurroughsB550b5500'
'1-7Control Data1700cdc1700'
'1-8Data GeneralNova, Eclipseeclipse nova'
'1-9Digital Equipment CorporationDEC systems and appliances'
'1-9-112-bit systemsPDP8pdp8'
'1-9-216-bit systemsPDP11/03,04,05,20,23,23+,24,34,40,44,45,53,60,70,73,738,83,84,93,94pdp11'
'1-9-318-bit systemsPDP1, 4, 7, 9, 15, TX-0(MIT-LL)pdp1 pdp4 pdp7 pdp9 pdp15 uc15 tx-0'
'1-9-432-bit systemsVAX'
'1-9-4-1Large VAX systemsVAX730,750,780,8200,8600vax730 vax750 vax780 vax8200 vax8600'
'1-9-4-2VLSI VAX systemsMicroVAX1,2,2000,3100,4000,rtVAX, and VAXstationsmicrovax1 microvax2 microvax2000 microvax3100 microvax3100m80 microvax3100e microvax3900 rtvax1000 vax vaxstation3100m30 vaxstation3100m38 vaxstation3100m76 vaxstation4000m60 vaxstation4000vlc'
'1-9-536-bit systemsPDP6, KA10, KI10, KL10, KS10pdp6 pdp10-ka pdp10-ki pdp10-kl pdp10-ks pdp10'
'1-9-664-bit systemsAlpha'
'1-9-7network appliancesInfoserversinfoserver100 infoserver150vxt infoserver1000'
'1-10General TurtleTT2500 tt2500'
'1-11GRI ComputerGRI-99, 909gri'
'1-12Hewlett-PackardHP2100, HP3000hp2100 hp3000'
'1-13HoneywellH316, 516h316'
'1-14IMLACPDS-1imlac'
'1-15Intel Microprocessor Data SystemsMD5, scelbiintel-mds scelbi'
'1-16Interdata16 and 32-bitid16 id32'
'1-17IBM1401, 1620, 650, 701, 704, 7070, 7080, 7090, 7094, System/3, and 1130i1401 i1620 i650 i701 i704 i7070 i7080 i7090 i7094 ibm1130 s3'
'1-18Royal-McbeeLGP 21, 30lgp'
'1-19SAGE Inc.SAGE'
'1-20Scientific Data SystemsSDS 940sds'
'1-21System Engineering LabSEL32sel32'
'1-22Russian computersBESM6besm6'
'1-23SouthWest Technical Productsswtp 6800mp-a and -a2swtp6800mp-a swtp6800mp-a2'
'1-24University of ManchesterSSEMssem'
'1-25XeroX Data SystemsSigmasigma'
)

MKDOC=
MKBIN=
! [ -d "$DSTDIR/doc" ] && MKDOC="mkdir -p -v $DSTDIR/doc"
! [ -d "$DSTDIR/bin" ] && MKBIN="mkdir -p -v $DSTDIR/bin"

function dofiles() {
    local FILES="$*"

    if [ -n "$REMOVE" ]; then
        for F in $FILES; do
            if [[ "$F" =~ \.(?:txt|doc|pdf)$ ]]; then
                rm -v "$DSTDIR/doc/$F"
            else
                rm -v "$DSTDIR/bin/$F"
            fi
        done
    else
        for F in $FILES; do
            if [[ "$F" =~ \.(?:txt|doc|pdf)$ ]]; then
                $MKDOC && MKDOC=
                cp -p -v "$SRCDIR/$F" "$DSTDIR/doc/"
            else
                $MKBIN && MKBIN=
                cp -p -v "$SRCDIR/$F" "$DSTDIR/bin/"
            fi
        done
    fi
}

# List

if [ -z "$ACTION" ]; then
    for (( i=0; i < ${#FEATURES[@]}; ++i )) ; do
        decode "$i"
        printf "%s %s - %s\n" "${PAD:0:$((depth*2))}" "$TITLE" "$DESC"
    done

    exit
fi

# Select by name?
if [[ $# -gt 0 ]]; then
    die "No parameters supported"

    while [[ $# -gt 0 ]]; do
        echo "$1"
        shift 1
    done

    exit
fi

# Interactive

cat <<EOF
Select simulators to $ACTION

All    - ${ACTION}s all simulators in group
None   - ${ACTION}s none of the simulators in group
Choose - ${ACTION}s common components and prompts for sub-groups

<CR> will use the default response, if set with -a or -n
Ctrl/C will quit (with partial results)

EOF

for (( i=0; i < ${#FEATURES[@]}; )) ; do
    decode "$i"

    if [ -z "$FILES" ]; then
       # Skip if this feature and all its subfeatures have no files
       sim_present=
       for(( j=i+1; j < ${#FEATURES[@]}; ++j )) ; do
            decode "$j" "sub_"
            if [[ "${sub_TAG:0:${#TAG}}" != "$TAG" ]] ; then break; fi
            if [ -n "$sub_FILES" ]; then
                sim_present=1
                break
            fi
       done
       if [ -z "$sim_present" ]; then
           (( ++i ))
           continue
       fi
    fi

    # Find depth of next feature

    if [[ $((i+1)) -lt ${#FEATURES[@]} ]]; then
        decode "$(( i+1 ))" "next_"
    else
        next_depth=-1
    fi

    printf "%s %s - %s: " "${PAD:0:$((depth*2))}" "$TITLE" "$DESC"

    # No subfeature choice if next feature depth > this
    xpn=
    if [ -n "$next_TAG" ] && (( next_depth > depth  )); then
        xpn=y
    fi
    # Prompt for disposition
    shopt -s nocasematch
    while true; do
        if [ -n "$xpn" ]; then
            read -e -r -p "$ACTION [All, Choose, None]: " REPLY
            [ -z "$REPLY" ] && REPLY="$DEFAULT"
            if [[ "$REPLY" =~ ^((a(l(l)?)?)|(C(h(o(o(s(e)?)?)?)?)?)|(N(o(n(e)?)?)?))$ ]] ; then
               break
            fi
        else
            read -e -r -p "$ACTION [All, None]: " REPLY
            [ -z "$REPLY" ] && REPLY="$DEFAULT"
            if [[ "$REPLY" =~ ^((a(l(l)?)?)|(N(o(n(e)?)?)?))$ ]] ; then
               break
            fi
        fi
        echo "Choose one of the options offered"
    done
    shopt -u nocasematch
    if ! [[ "$REPLY" =~ ^[Cc] ]]; then
        # All or None of the files & subfeatures
        [[ "$REPLY" =~ ^[Aa] ]] && dofiles "$FILES"
        (( ++i ))
        while [[ i -lt ${#FEATURES[@]} ]] ; do
            decode "$i" "next_"
            if [[ "${next_TAG:0:${#TAG}}" != "$TAG" ]]; then
                break
            fi
            [[ "$REPLY" =~ ^[Aa] ]] && dofiles "$next_FILES"
            (( ++i ))
        done
        continue
    fi
    # Choose subfeatures (Handle any files attached to the feature)
    dofiles "$FILES"
    (( ++i ))
done

exit
