#!/bin/bash
# console-config/src/lib-scripts/timing-common.sh
#
#  Copyright: ©2013, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
# Routines that are used throughout all the different timing config modules.
#



# assert()
#  Print an error message, dump some diagnostics, and exit the program.
assert() {
    reset
    clear
    echo "============================" >&2
    set 1>&2
    echo "============================" >&2
    echo "An error occurred. Please contact support@guralp.com with this" >&2
    echo "message and the information above." >&2
    echo "$*" >&2
    echo "============================" >&2
    exit 1
}



# Machinery for dialog
#  DIALOG_RESULTFILE is where we save results to. We use an intermediate
#  temp file to capture the result because running within backticks causes
#  dialog to fail.
declare -a MENU
MENU_EXTRA_ARGS=""

DIALOG_RESULTFILE="`mktemp`"
trap "rm -f \"${DIALOG_RESULTFILE}\"" EXIT

DIALOG_DEFAULT_W="60"



# write_config_file()
#  Safely write a configuration file. Data to write is piped on stdin, and
#  the filename is passed as argument $1. Exits on error.
write_config_file() {
    local FILENAME="$1"
    local TMP_FILE="$1.new"

    echo "Writing configuration file \"${FILENAME}\"..."

    cat > "${TMP_FILE}"
    if [ $? -ne 0 -o ! -s "${TMP_FILE}" ]
    then
        echo "Writing configuration file \"${FILENAME}\" failed." >&2
        exit 1
    fi

    mv -f "${TMP_FILE}" "${FILENAME}"
    [ $? -ne 0 ] && exit 1

    return 0
}



# write_timing_config()
#  Writes the main timing configuration file. Arguments are as follows:
#  $1 → name of mode ("direct_gps", "ntp", etc.)
#  $2 → true to start ntp, false otherwise
#  $3 → true to start ntpshmgsl, false otherwise
#  $4 → true to start gpsstatusd, false otherwise
write_timing_config() {
    local MODE="$1"
    local NTP="$2"
    local NTPSHMGSL="$3"
    local GPSSTATUSD="$4"

    ( cat <<EOF
# ${TIMING_CONFIG}
#  Written at `isodate -me` by $0
mode = ${MODE}
start_ntp = ${NTP}
start_ntpshmgsl = ${NTPSHMGSL}
start_gpsstatusd = ${GPSSTATUSD}
EOF
    ) | write_config_file "${TIMING_CONFIG}"
}



# write_ntp_preamble()
#  Generates common ntp.conf preamble. This is used regardless of NTP mode
#  (networked, GPS, SHM).
write_ntp_preamble() {
    cat <<EOF
# ${NTP_CONFIG}
#  Written at `isodate -me` by $0

driftfile /var/lib/ntp/ntp.drift
restrict default nomodify nopeer noquery
restrict 127.0.0.1

EOF
}



# vim: ts=4:sw=4:expandtab:syntax=sh
