#!/bin/bash

set -eu
set -o pipefail

# A little slow, but works well.
which_vnc=TightVNC

case "$(hostname)" in
    dstromberg-precision-3530)
        which_vnc=TigerVNC
        ;;
esac

case "$which_vnc" in
    TurboVNC)
        extra_opts=""
        vncviewer=/opt/TurboVNC/bin/vncviewer
        ;;
    TigerVNC)
        # Not completely sure -PreferredEncoding was for Tiger
        extra_opts="-shared=1 -PreferredEncoding=ZRLE"
        vncviewer=vncviewer
        ;;
    TightVNC)
        extra_opts="shared=1"
        vncviewer=vncviewer
        ;;
    *)
        echo "$0: internal error: \$which_vnc has a strange value: $which_vnc" 1>&2
        exit 1
        ;;
esac

insecure=False
host=@

function usage
{
    retval="$1"
    case "$retval" in
        0) ;;
        *) exec 1>&2 ;;
    esac

    echo "Usage: $0 --insecure --host localhost:1 --help"
    echo
    echo "With --insecure, it is recommended to use an ssh tunnel or similar."

    exit "$retval"
}

while [ "$#" -ge 1 ]
do
    case "$1" in
        --insecure)
            insecure=True
            ;;
        --host)
            host="$2"
            shift
            ;;
        --help|-h)
            usage 0
            ;;
        *)
            echo "$0: unrecognized option: $1" 1>&2
            usage 1
            ;;
    esac
    shift
done

all_good=True
case "$host" in
    @)
        echo "$0: --host is a required option: EG example.com:1" 1>&2
        all_good=False
        ;;
esac

case "$all_good" in
    True) ;;
    False)
        echo "$0: preflight check failed" 1>&2
        usage 1
        ;;
    *)
        echo "$0: internal error: \$all_good has a strange value: $all_good" 1>&2
        exit 1
        ;;
esac
        
case "$insecure" in
    False)
        case "$which_vnc" in
            TigerVNC)
                sectypes="-SecurityTypes=VeNCrypt,TLSVnc"
                extra_opts="-shared"
                ;;
            TightVNC|TurboVNC)
                # These likely don't support encryption.
                echo "$0: $which_vnc does not support encryption (?)" 1>&2
                exit 1
                ;;
            *)
                ;;
        esac
        ;;
    True)
        sectypes=""
        ;;
    *)
        echo "$0: internal error: \$insecure not True or False: $insecure" 1>&2
        exit 1
        ;;
esac

# intentionally not quoting $extra_opts and $sectypes
"$vncviewer" $extra_opts $sectypes "$host"