#!/bin/bash

# Detect environment

RC=1
# If necessary, read config from 'fcfg'
LOCAL_BIN_DIR=`dirname \`readlink -f $0\``
LOCAL_CFG="${LOCAL_BIN_DIR}/fcfg"
if [ ! "${FCFG_HAS_BEEN_SOURCED}" = "1" ];then
    if [ ! -e "${LOCAL_CFG}" ];then
        printf "Read config file...\t\tERROR\n"
        printf "'${LOCAL_CFG}' does not exist.\n"
        printf "Run 'fsetup' without any arguments to create a template for 'fcfg'.\n"
        exit $RC
    fi
    . "${LOCAL_CFG}"
    if [ $? -ne 0 ];then
        printf "Source config file...\t\tERROR\n"
        printf "Could not source '${LOCAL_CFG}'.\n"
        exit $RC
    fi
fi

# Detect Fossil executable
printf "Detect Fossil executable...\t\t"
FOSSIL=`which fossil 2>/dev/null`
if [ -z "${FOSSIL}" ];then
    printf "ERROR (fossil not found, please install)\n"
    exit $RC
else
    printf "OK (${FOSSIL})\n"
fi

# Detect SSH client executable
printf "Detect SSH client executable...\t\t"
SSH_CLIENT=`which ssh 2>/dev/null`
if [ -z "${SSH_CLIENT}" ];then
    printf "ERROR (ssh not found, please install)\n"
    exit $RC
else
    printf "OK (${SSH_CLIENT})\n"
fi

# Detect platform
printf "Detect platform...\t\t\t"
uname -a| grep -q '^MSYS\|^MINGW'
RC=$?
if [ "${RC}" -eq "0" ]; then
    # MSYS/MSYS2/MINGW32/MINGW64
    BASE=${BASE_MINGW}
    printf "OK (MSYS/MINGW)\n"
else
    uname -a| grep -q '^CYGWIN'
    RC=$?
    if [ "${RC}" -eq "0" ]; then
        # CYGWIN
        BASE=${BASE_CYGWIN}
    printf "OK (CYGWIN)\n"
    else
        # UNIX/Mac OSX
        BASE=${BASE_UNIX}
        printf "OK (Linux/UNIX/Mac/Whatever)\n"
    fi
fi
LOCAL_REPOS_DIR="${BASE}/${REPOS_DIR}"
LOCAL_SRC_MAIN="${BASE}/${CONTAINER_DIR}"

# Handle non-standard SSH port
if [ ${REMOTE_PORT} -ne 22 ];then
    SSH_COMMAND="ssh -p ${REMOTE_PORT}"
    SCP_COMMAND="scp -p -P ${REMOTE_PORT}"
    fossil settings --global ssh-command "${SSH_COMMAND}"
fi

FENV_HAS_BEEN_SOURCED=1
