#!/bin/sh
### BEGIN INIT INFO
# Provides:          recordum-station
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Start-Before:    openvpn
# Short-Description: Apply station identity and update its machine patch
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin
PATCH_NAME='airpointer-2026-00846'
HOST_NAME='airpointer-2026-00846'
PORTAL_DOMAIN='recordum.net'
LOG_FILE=/var/log/recordum/recordum-station.log

mkdir -p "${LOG_FILE%/*}" || exit 1
exec >> "$LOG_FILE" 2>&1 || exit 1
printf '\n[%s] action=%s\n' "$(date '+%F %T')" "${1:-unknown}"

log() {
    logger -t recordum-station "$*" 2>/dev/null || true
}

set_station_hostname() {
    printf '%s\n' "$HOST_NAME" > /etc/hostname || return 1
    hostname "$HOST_NAME"
}

update_station_hosts() {
    # Replace the prior managed block and the old postinst's entries. Preserve
    # the base hosts file through its environment marker when that marker exists.
    sed -i \
        -e '/^# recordum-station managed hosts$/,$d' \
        -e '/^127\.0\.0\.1[[:space:]]\+'"$HOST_NAME"'[[:space:]]*$/d' \
        -e '/^::1[[:space:]]\+'"$HOST_NAME"'[[:space:]]*$/d' \
        -e '/^10\.10\.1\.100[[:space:]]\+updates-test\.mlu\.local[[:space:]]*$/d' \
        -e '/^10\.10\.1\.100[[:space:]]\+v2\.repo\.mlu\.local[[:space:]]*$/d' \
        /etc/hosts || return 1

    if grep -q '^# Following ' /etc/hosts; then
        sed -i -e '/^# Following / q' /etc/hosts || return 1
    fi

    cat <<EOF >> /etc/hosts
# recordum-station managed hosts
127.0.0.1 $HOST_NAME
::1       $HOST_NAME
10.10.1.100 updates-test.mlu.local
10.10.1.100 v2.repo.mlu.local
EOF
}

hostname_resolves_to_localhost() {
    getent hosts "$HOST_NAME" 2>/dev/null |
        awk '$1 == "127.0.0.1" || $1 == "::1" { found = 1 } END { exit !found }'
}

ensure_station_localhost_resolution() {
    if hostname_resolves_to_localhost; then
        return 0
    fi

    sed -i -e '/^127\.0\.0\.1[[:space:]]\+'"$HOST_NAME"'[[:space:]]*$/d' /etc/hosts || return 1
    sed -i "1i127.0.0.1 $HOST_NAME" /etc/hosts || return 1
    hostname_resolves_to_localhost
}

configure_openvpn() {
    config=/etc/openvpn/client.conf
    [ -f "$config" ] || return 0

    version=$(dpkg-query -W -f='${Version}' openvpn 2>/dev/null) || return 0
    [ -n "$version" ] || return 0

    # Toggle only the portal-host directives, leaving the subject-form example alone.
    if dpkg --compare-versions "$version" ge 2.3; then
        sed -i -E \
            -e 's|^[[:space:]]*tls-remote[[:space:]]+portal-eu\.recordum\.net[[:space:]]*$|# tls-remote portal-eu.recordum.net|' \
            -e 's|^[[:space:]]*#[[:space:]]*verify-x509-name[[:space:]]+portal-eu\.recordum\.net[[:space:]]+name[[:space:]]*$|verify-x509-name portal-eu.recordum.net name|' \
            "$config"
    else
        sed -i -E \
            -e 's|^[[:space:]]*#[[:space:]]*tls-remote[[:space:]]+portal-eu\.recordum\.net[[:space:]]*$|tls-remote portal-eu.recordum.net|' \
            -e 's|^[[:space:]]*verify-x509-name[[:space:]]+portal-eu\.recordum\.net[[:space:]]+name[[:space:]]*$|# verify-x509-name portal-eu.recordum.net name|' \
            "$config"
    fi
}

configure_station() {
    if ! update_station_hosts; then
        log 'unable to update station hosts entries'
        return 1
    fi

    if [ -x /usr/local/bin/recordum_hostname ]; then
        if ! /usr/local/bin/recordum_hostname "$HOST_NAME" "$PORTAL_DOMAIN"; then
            log 'recordum_hostname failed'
        fi
    fi

    if ! set_station_hostname; then
        log "unable to set hostname to $HOST_NAME"
        return 1
    fi

    if ! ensure_station_localhost_resolution; then
        log "station hostname $HOST_NAME does not resolve to localhost"
        return 1
    fi

    if ! configure_openvpn; then
        log 'unable to select OpenVPN certificate verification directives'
        return 1
    fi
}

start_station() {
    if ! configure_station; then
        log 'station configuration did not complete successfully'
    fi

    if apt-get update; then
        if ! DEBIAN_FRONTEND=noninteractive apt-get install -y --only-upgrade "$PATCH_NAME"; then
            log "unable to upgrade machine patch $PATCH_NAME"
        fi
    else
        log 'apt metadata refresh failed; skipping machine patch upgrade'
    fi

    # Installing an updated patch replaces client.conf, so apply the version
    # specific directives again before OpenVPN is allowed to start.
    if ! configure_openvpn; then
        log 'unable to reapply OpenVPN certificate verification directives'
    fi
}

case "$1" in
    configure)
        configure_station
        exit $?
        ;;
    start)
        start_station
        ;;
    stop)
        ;;
    restart|force-reload)
        start_station
        ;;
    *)
        echo "Usage: $0 {configure|start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0
