#!/usr/bin/env bash # # AIS-catcher Installation Script # # Description: # Automated installation script for AIS-catcher on Debian, Ubuntu and Fedora # systems. Supports both package-based (.deb/.rpm) and source-based # installations. # # Usage: # sudo ./aiscatcher-install [OPTIONS] # # Options: # -p, --package Install from pre-built package (faster, recommended) # -i, --interactive Source build with interactive feature selection # --no-systemd Skip systemd service installation (useful for containers) # -h, --help Display this help message # # Requirements: # - Must be run as root (use sudo) # - Debian-based system (Debian/Ubuntu/Raspbian) or Fedora # - Internet connection for downloading packages/source # # Author: AIS-catcher Project # License: See LICENSE file # set -euo pipefail # Display usage information usage() { cat << EOF AIS-catcher Installation Script Usage: sudo $0 [OPTIONS] Options: -p, --package Install from pre-built package (faster, recommended) -i, --interactive Source build with interactive feature selection (forces source path) -b, --branch Specify git branch to clone (default: main) -M, --managed Run the service in managed mode (-E ${MANAGED_CONFIG_FILE} ${MANAGED_BIND}) --no-systemd Skip systemd service installation (useful for containers) --no-user Skip user creation and run as root (useful for containers) --set-reboot-on-failure [BURST [SEC]] Enable reboot watchdog (default: 3 restarts in 1800s) --unset-reboot-on-failure Disable automatic reboot on repeated failures --set-auto-restart Enable automatic service restart on crash (Restart=always) --unset-auto-restart Disable automatic service restart on crash (Restart=no) -h, --help Display this help message Examples: sudo $0 --package # Install from pre-built package sudo $0 # Build and install from source (main branch) sudo $0 -i # Source build, asks per-feature what to include sudo $0 -b develop # Build from develop branch sudo $0 --no-systemd --no-user # Docker/container installation sudo $SCRIPT_NAME --set-reboot-on-failure # Enable reboot watchdog (no reinstall needed) sudo $SCRIPT_NAME --unset-reboot-on-failure # Disable reboot watchdog (no reinstall needed) sudo $SCRIPT_NAME --set-auto-restart # Enable auto-restart on crash (no reinstall needed) sudo $SCRIPT_NAME --unset-auto-restart # Disable auto-restart on crash (no reinstall needed) For more information, visit: https://docs.aiscatcher.org/ EOF exit 0 } # Check if running as root require_root() { if [ "$EUID" -ne 0 ]; then local hint_args hint_args=$(printf '%q ' "$@") if [[ -t 1 ]]; then echo -e "\033[1;31mError: This script must be run as root\033[0m" >&2 echo -e "\033[1;33mPlease run: sudo $0 ${hint_args% }\033[0m" >&2 else echo "Error: This script must be run as root" >&2 echo "Please run: sudo $0 ${hint_args% }" >&2 fi exit 1 fi } # Constants SCRIPT_NAME=$(basename "$0") readonly SCRIPT_NAME LOG_FILE="/var/log/${SCRIPT_NAME%.*}.log" readonly LOG_FILE readonly CONFIG_DIR="/etc/AIS-catcher" readonly PLUGIN_DIR="${CONFIG_DIR}/plugins" readonly DBMS_DIR="${CONFIG_DIR}/DBMS" readonly README_DIR="${CONFIG_DIR}/README" readonly LIB_DIR="/usr/lib/ais-catcher" readonly CONFIG_FILE="${CONFIG_DIR}/config.json" readonly CMD_FILE="${CONFIG_DIR}/config.cmd" readonly MANAGED_CONFIG_FILE="${CONFIG_DIR}/aiscatcher.json" readonly MANAGED_BIND="0.0.0.0:8118" readonly SERVICE_NAME="ais-catcher.service" readonly SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}" readonly REBOOT_SERVICE_NAME="ais-catcher-reboot.service" readonly REBOOT_SERVICE_FILE="/etc/systemd/system/${REBOOT_SERVICE_NAME}" readonly REBOOT_BURST_DEFAULT=3 readonly REBOOT_INTERVAL_DEFAULT=1800 MAKE_JOBS=$(nproc) _mem_gb=$(awk '/MemTotal/ {print int($2 / 1024 / 1024)}' /proc/meminfo 2>/dev/null || echo 1) [[ "$_mem_gb" -lt 1 ]] && _mem_gb=1 [[ "$_mem_gb" -lt "$MAKE_JOBS" ]] && MAKE_JOBS="$_mem_gb" readonly MAKE_JOBS # Global variables INSTALL_PACKAGE=false INTERACTIVE=false SKIP_SYSTEMD=false SKIP_USER=false MANAGED=false BRANCH="main" SERVICE_STATE="" SERVICE_START_FAILED=false SET_REBOOT="" REBOOT_BURST="${REBOOT_BURST_DEFAULT}" REBOOT_INTERVAL="${REBOOT_INTERVAL_DEFAULT}" SET_AUTO_RESTART="" INSTALL_REQUESTED=false TMP_DIR="" DEB_TMP_DIR="" # User-facing CMake feature toggles (defaults mirror CMakeLists.txt option() lines). # Infrastructure libs (SOXR, SAMPLERATE, ZLIB, OPENSSL) and link-style toggles # (RTLSDR_STATIC, HYDRASDR_STATIC, RBIT) are intentionally not exposed # interactively — they stay at their CMake defaults. FEATURE_RTLSDR=ON FEATURE_AIRSPY=ON FEATURE_AIRSPYHF=ON FEATURE_HACKRF=ON FEATURE_HYDRASDR=ON FEATURE_SDRPLAY=ON FEATURE_SOAPYSDR=OFF FEATURE_PSQL=ON FEATURE_SQLITE=ON FEATURE_WEBVIEWER=ON readonly FEATURES=(RTLSDR AIRSPY AIRSPYHF HACKRF HYDRASDR SDRPLAY SOAPYSDR PSQL SQLITE WEBVIEWER) # Color constants (using ANSI escape codes) if [[ -t 1 ]]; then readonly COLOR_RESET="\033[0m" readonly COLOR_BOLD="\033[1m" readonly COLOR_RED="\033[0;31m" readonly COLOR_GREEN="\033[0;32m" readonly COLOR_YELLOW="\033[0;33m" readonly COLOR_BLUE="\033[0;34m" readonly COLOR_CYAN="\033[0;36m" readonly COLOR_BOLD_RED="\033[1;31m" readonly COLOR_BOLD_GREEN="\033[1;32m" readonly COLOR_BOLD_YELLOW="\033[1;33m" readonly COLOR_BOLD_BLUE="\033[1;34m" else readonly COLOR_RESET="" readonly COLOR_BOLD="" readonly COLOR_RED="" readonly COLOR_GREEN="" readonly COLOR_YELLOW="" readonly COLOR_BLUE="" readonly COLOR_CYAN="" readonly COLOR_BOLD_RED="" readonly COLOR_BOLD_GREEN="" readonly COLOR_BOLD_YELLOW="" readonly COLOR_BOLD_BLUE="" fi # Logger function with color support log() { local level="$1" shift local color="" local timestamp="$(date +'%Y-%m-%d %H:%M:%S')" case "$level" in ERROR) color="${COLOR_BOLD_RED}" ;; WARN) color="${COLOR_BOLD_YELLOW}" ;; INFO) color="${COLOR_BOLD_GREEN}" ;; *) color="${COLOR_RESET}" ;; esac # Print to terminal with color; %s ensures backslashes in message text are not interpreted printf "${COLOR_CYAN}[${timestamp}]${COLOR_RESET} ${color}[${level}]${COLOR_RESET} %s\n" "$*" # Log to file without color codes printf '[%s] [%s] %s\n' "${timestamp}" "${level}" "$*" >> "$LOG_FILE" } # Error handler error_exit() { log "ERROR" "$1" exit 1 } # Runs on every exit, also after Ctrl-C: a service stopped for the installation is put back cleanup() { if [[ -n "$SERVICE_STATE" ]]; then log "WARN" "Installation did not finish; restoring the service's state" restore_service_state || log "WARN" "Failed to restore service state" fi log "INFO" "Cleaning up temporary directory ${TMP_DIR}" rm -rf "$TMP_DIR" if [[ -n "$DEB_TMP_DIR" ]]; then rm -rf "$DEB_TMP_DIR" fi } # Prompt for a yes/no answer with a default; echoes ON or OFF. # Args: $1 label, $2 default (ON|OFF) prompt_yes_no() { local label="$1" default="$2" local suffix if [[ "$default" == "ON" ]]; then suffix="[Y/n]"; else suffix="[y/N]"; fi while true; do local answer read -r -p "$(printf "${COLOR_BOLD}%s${COLOR_RESET} %s: " "$label" "$suffix")" answer # shellcheck disable=SC2155 # locale lowercasing needs ${var,,} local lower="${answer,,}" case "${lower:-${default,,}}" in on|y|yes|true|1) echo "ON"; return 0 ;; off|n|no|false|0) echo "OFF"; return 0 ;; *) echo "Please answer y or n." >&2 ;; esac done } # Walk the user through per-feature toggles. # Sets the FEATURE_* globals from current defaults, and aborts if the user # rejects the summary. Requires a TTY. interactive_feature_select() { [[ -t 0 ]] || error_exit "Interactive mode requires a TTY (stdin is not a terminal)" echo echo -e "${COLOR_BOLD_BLUE}Interactive feature selection${COLOR_RESET}" echo -e "Press Enter to accept the default shown in capitals." echo echo -e "${COLOR_BOLD}SDR hardware${COLOR_RESET}" FEATURE_RTLSDR=$(prompt_yes_no " RTL-SDR (RTL2832-based dongles)" "$FEATURE_RTLSDR") FEATURE_AIRSPY=$(prompt_yes_no " Airspy" "$FEATURE_AIRSPY") FEATURE_AIRSPYHF=$(prompt_yes_no " Airspy HF+" "$FEATURE_AIRSPYHF") FEATURE_HACKRF=$(prompt_yes_no " HackRF" "$FEATURE_HACKRF") FEATURE_HYDRASDR=$(prompt_yes_no " HydraSDR" "$FEATURE_HYDRASDR") FEATURE_SDRPLAY=$(prompt_yes_no " SDRplay (proprietary SDK required)" "$FEATURE_SDRPLAY") FEATURE_SOAPYSDR=$(prompt_yes_no " SoapySDR" "$FEATURE_SOAPYSDR") echo echo -e "${COLOR_BOLD}Inputs / outputs${COLOR_RESET}" FEATURE_PSQL=$(prompt_yes_no " PostgreSQL output (-D)" "$FEATURE_PSQL") FEATURE_SQLITE=$(prompt_yes_no " SQLite (offline map tiles and -D output)" "$FEATURE_SQLITE") echo echo -e "${COLOR_BOLD}Other${COLOR_RESET}" FEATURE_WEBVIEWER=$(prompt_yes_no " Embedded web UI (-N)" "$FEATURE_WEBVIEWER") echo echo -e "${COLOR_BOLD_BLUE}Selected features:${COLOR_RESET}" local f vname for f in "${FEATURES[@]}"; do vname="FEATURE_$f" printf " %-12s %s\n" "$f" "${!vname}" done echo local confirm read -r -p "Proceed with these settings? [Y/n]: " confirm if [[ "${confirm,,}" =~ ^(n|no)$ ]]; then log "INFO" "Installation aborted by user" exit 0 fi } # Cancel any pending reboot and stop the watchdog service. # Safe to call unconditionally — harmless if nothing is pending or running. cancel_reboot_watchdog() { shutdown -c 2>/dev/null || true systemctl stop "$REBOOT_SERVICE_NAME" 2>/dev/null || true log "INFO" "Reboot watchdog cancelled (pending shutdown cleared, service stopped)" } # Replace a directive if present in FILE, otherwise insert it under its section header. sed_replace_or_insert() { local key="$1" val="$2" section="$3" file="$4" if grep -q "^${key}=" "$file"; then sed -i "s/^${key}=.*/${key}=${val}/" "$file" else sed -i "/^\[${section}\]/a ${key}=${val}" "$file" fi } # Reload systemd and reset the service failure counter. reload_and_reset_service() { systemctl daemon-reload || error_exit "Failed to reload systemd" log "INFO" "Resetting failure counter for ${SERVICE_NAME}" systemctl reset-failed "$SERVICE_NAME" 2>/dev/null || log "WARN" "Failed to reset failure counter" } # Log whether new policy settings will take effect now or at next restart. # Neither toggle handler restarts the service, so we just check current state for messaging. log_service_policy_notice() { local policy_desc="$1" if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then log "INFO" "${SERVICE_NAME} is running — ${policy_desc} will apply from the next restart" else log "INFO" "${SERVICE_NAME} was not running — configuration updated" fi } ################################################################################ # REBOOT-ON-FAILURE TOGGLE (standalone, no reinstall needed) ################################################################################ # Enable or disable the reboot watchdog by updating StartLimitBurst/Interval in the service file handle_reboot_setting() { if [[ ! -f "$SERVICE_FILE" ]]; then error_exit "Service file not found at ${SERVICE_FILE} — is AIS-catcher installed?" fi if [[ "$SET_REBOOT" == "true" ]]; then sed_replace_or_insert StartLimitBurst "${REBOOT_BURST}" Unit "$SERVICE_FILE" sed_replace_or_insert StartLimitIntervalSec "${REBOOT_INTERVAL}" Unit "$SERVICE_FILE" # Add OnFailure= if not already present if ! grep -q "^OnFailure=" "$SERVICE_FILE"; then sed -i "/^After=network.target/a OnFailure=${REBOOT_SERVICE_NAME}" "$SERVICE_FILE" fi log "INFO" "Reboot on failure enabled (burst: ${REBOOT_BURST}, interval: ${REBOOT_INTERVAL}s)" else sed_replace_or_insert StartLimitBurst 0 Unit "$SERVICE_FILE" sed_replace_or_insert StartLimitIntervalSec 0 Unit "$SERVICE_FILE" # Remove OnFailure= line — with burst=0 it fires on every crash, not just limit-hit sed -i "/^OnFailure=/d" "$SERVICE_FILE" log "INFO" "Reboot on failure disabled" fi reload_and_reset_service # No restart needed: Restart=, StartLimitBurst=, OnFailure= are systemd policy directives # that take effect on the next crash/start — daemon-reload is sufficient. log_service_policy_notice "new watchdog settings" } ################################################################################ # AUTO-RESTART TOGGLE (standalone, no reinstall needed) ################################################################################ # Enable or disable automatic service restart by updating Restart= in the service file handle_auto_restart_setting() { if [[ ! -f "$SERVICE_FILE" ]]; then error_exit "Service file not found at ${SERVICE_FILE} — is AIS-catcher installed?" fi if [[ "$SET_AUTO_RESTART" == "true" ]]; then sed_replace_or_insert Restart always Service "$SERVICE_FILE" log "INFO" "Auto-restart enabled (Restart=always)" else sed_replace_or_insert Restart no Service "$SERVICE_FILE" log "INFO" "Auto-restart disabled (Restart=no)" fi reload_and_reset_service # No restart needed: Restart= is a systemd policy directive that takes effect on the # next crash/start — daemon-reload is sufficient and avoids unnecessary interruption. log_service_policy_notice "new restart policy" } ################################################################################ # UTILITY FUNCTIONS (Used by both package and source installations) ################################################################################ # Package manager abstraction: apt (Debian/Ubuntu/Raspbian) or dnf (Fedora). if command -v apt-get &>/dev/null; then PKG_MANAGER="apt" elif command -v dnf &>/dev/null; then PKG_MANAGER="dnf" else PKG_MANAGER="" fi readonly PKG_MANAGER require_package_manager() { if [[ -z "$PKG_MANAGER" ]]; then error_exit "No supported package manager found (need apt-get or dnf)" fi } pkg_update() { if [[ "$PKG_MANAGER" == "apt" ]]; then apt-get update else dnf -y makecache fi } pkg_install() { if [[ "$PKG_MANAGER" == "apt" ]]; then DEBIAN_FRONTEND=noninteractive apt-get install -y \ -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold "$@" else dnf -y install "$@" fi } # Check for conflicting existing service check_existing_service() { if systemctl is-enabled aiscatcher.service &>/dev/null; then log "ERROR" "Detected existing aiscatcher.service. Please disable it first with:" log "ERROR" "systemctl disable aiscatcher.service" log "ERROR" "Then run this script again." exit 1 fi } # Detect system information (OS, version, architecture). # apt systems identify by codename + dpkg arch (debian_bookworm_arm64), # dnf systems by version number + machine arch (fedora_44_x86_64). get_system_info() { local os version arch if [ -f /etc/os-release ]; then . /etc/os-release if [ "${ID:-}" = "raspbian" ]; then os="debian" else os="${ID:-}" fi if [[ "$PKG_MANAGER" == "dnf" ]]; then version="${VERSION_ID:-}" else version="${VERSION_CODENAME:-}" fi [[ -z "$os" ]] && error_exit "Could not determine OS ID from /etc/os-release" [[ -z "$version" ]] && error_exit "Could not determine OS version from /etc/os-release" else os=$(uname -s) || error_exit "Failed to determine OS name (uname -s)" version=$(uname -r) || error_exit "Failed to determine OS version (uname -r)" fi if [[ "$PKG_MANAGER" == "dnf" ]]; then arch=$(uname -m) || error_exit "Failed to determine system architecture (uname -m)" else arch=$(dpkg --print-architecture) || error_exit "Failed to determine system architecture (dpkg --print-architecture)" fi echo "${os}_${version}_${arch}" } ################################################################################ # SOURCE INSTALLATION FUNCTIONS ################################################################################ # Install build dependencies for source compilation. # OpenSSL/zlib stay required (always-on infrastructure features). Per-feature # optional packages are only installed when the matching FEATURE_* is ON. install_source_build_dependencies() { local required_deps optional_deps="" if [[ "$PKG_MANAGER" == "apt" ]]; then required_deps="git cmake build-essential pkg-config libssl-dev zlib1g-dev libusb-1.0-0-dev curl" [[ "$FEATURE_PSQL" == "ON" ]] && optional_deps+=" libpq-dev" [[ "$FEATURE_SQLITE" == "ON" ]] && optional_deps+=" libsqlite3-dev" [[ "$FEATURE_AIRSPY" == "ON" ]] && optional_deps+=" libairspy-dev" [[ "$FEATURE_AIRSPYHF" == "ON" ]] && optional_deps+=" libairspyhf-dev" [[ "$FEATURE_HACKRF" == "ON" ]] && optional_deps+=" libhackrf-dev" [[ "$FEATURE_SOAPYSDR" == "ON" ]] && optional_deps+=" libsoapysdr-dev" else required_deps="git cmake gcc-c++ make pkgconf-pkg-config openssl-devel zlib-devel libusb1-devel curl" [[ "$FEATURE_PSQL" == "ON" ]] && optional_deps+=" libpq-devel" [[ "$FEATURE_SQLITE" == "ON" ]] && optional_deps+=" sqlite-devel" [[ "$FEATURE_AIRSPY" == "ON" ]] && optional_deps+=" airspyone_host-devel" [[ "$FEATURE_AIRSPYHF" == "ON" ]] && optional_deps+=" airspyhf-devel" [[ "$FEATURE_HACKRF" == "ON" ]] && optional_deps+=" hackrf-devel" [[ "$FEATURE_SOAPYSDR" == "ON" ]] && optional_deps+=" SoapySDR-devel" fi log "INFO" "Installing required build dependencies: $required_deps" pkg_install $required_deps || error_exit "Failed to install required dependencies" if [[ -n "$optional_deps" ]]; then log "INFO" "Installing optional dependencies (failures allowed):$optional_deps" for pkg in $optional_deps; do if pkg_install "$pkg"; then log "INFO" "Installed $pkg" else log "WARN" "Could not install $pkg - corresponding feature may be unavailable" fi done else log "INFO" "No optional dependencies needed for the selected feature set" fi } # Install librtlsdr from source install_librtlsdr_from_source() { log "INFO" "Installing librtlsdr from source" git clone https://gitea.osmocom.org/sdr/rtl-sdr --depth 1 || error_exit "Failed to clone rtl-sdr repository" cd rtl-sdr || error_exit "Failed to change directory to rtl-sdr" mkdir build && cd build || error_exit "Failed to create and enter build directory" cmake ../ -DCMAKE_INSTALL_PREFIX="${LIB_DIR}" -DDETACH_KERNEL_DRIVER=ON -DINSTALL_UDEV_RULES=ON || error_exit "Failed to run cmake" make -j"$MAKE_JOBS" || error_exit "Failed to build rtl-sdr" make install || error_exit "Failed to install rtl-sdr" # ldconfig not needed: libraries are in a custom prefix and the RPATH in the AIS-catcher # binary points directly to ${LIB_DIR}/lib, so the dynamic linker finds them without it. cd ../.. || error_exit "Failed to return to parent directory" } # Install libhydrasdr from source install_libhydrasdr_from_source() { log "INFO" "Installing libhydrasdr from source" git clone https://github.com/hydrasdr/rfone_host.git --depth 1 || error_exit "Failed to clone rfone_host repository" cd rfone_host/libhydrasdr || error_exit "Failed to change directory to rfone_host/libhydrasdr" mkdir build && cd build || error_exit "Failed to create and enter build directory" cmake .. -DCMAKE_INSTALL_PREFIX="${LIB_DIR}" -DINSTALL_UDEV_RULES=ON || error_exit "Failed to run cmake" make -j"$MAKE_JOBS" || error_exit "Failed to build libhydrasdr" make install || error_exit "Failed to install libhydrasdr" cd ../../.. || error_exit "Failed to return to parent directory" } # Install SDR libraries from source (only for source build). # Each step is gated on its FEATURE_* flag so users disabling a feature # don't pay the clone+build cost or pollute ${LIB_DIR}. install_sdr_libraries_from_source() { # Create library directory mkdir -p "${LIB_DIR}" || error_exit "Failed to create library directory" # rtlsdr and hydrasdr from source (need custom cmake flags for udev rules) [[ "$FEATURE_RTLSDR" == "ON" ]] && install_librtlsdr_from_source [[ "$FEATURE_HYDRASDR" == "ON" ]] && install_libhydrasdr_from_source # Explicit success: under `set -e`, a trailing `[[ ]] && fn` whose test is # false makes the whole function return 1 (the && short-circuits, leaving # the test's exit code as the function's last status). That silently kills # the script before build_ais_catcher_from_source ever runs. return 0 } # Build AIS-catcher from source build_ais_catcher_from_source() { log "INFO" "Building AIS-catcher from branch: ${BRANCH}" git clone https://github.com/jvde-github/AIS-catcher.git --depth 1 --branch "${BRANCH}" || error_exit "Failed to download AIS-catcher (branch: ${BRANCH})" cd AIS-catcher # Set environment variables to find custom libraries export PKG_CONFIG_PATH="${LIB_DIR}/lib/pkgconfig:${PKG_CONFIG_PATH:-}" export CMAKE_PREFIX_PATH="${LIB_DIR}:${CMAKE_PREFIX_PATH:-}" # Build with rpath to custom library directory mkdir -p build && cd build local cmake_args=( -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_RPATH="${LIB_DIR}/lib;${LIB_DIR}" -DCMAKE_BUILD_RPATH="${LIB_DIR}/lib;${LIB_DIR}" ) # Per-feature toggles (mirror CMakeLists.txt option() names). local f vname for f in "${FEATURES[@]}"; do vname="FEATURE_$f" cmake_args+=("-D${f}=${!vname}") done cmake .. "${cmake_args[@]}" || error_exit "Failed to run cmake" make -j"$MAKE_JOBS" || error_exit "Failed to build AIS-catcher" cd ../.. install -m 755 AIS-catcher/build/AIS-catcher /usr/bin/AIS-catcher || error_exit "Failed to install AIS-catcher executable" } # Install additional files (plugins, DBMS, README, LICENSE) from source install_source_additional_files() { # Ensure the config directory exists before copying files into it. # Do not rely on mkdir -p "$PLUGIN_DIR" creating the parent as a side-effect. mkdir -p "$CONFIG_DIR" || error_exit "Failed to create config directory" log "INFO" "Installing plugins" mkdir -p "$PLUGIN_DIR" || error_exit "Failed to create plugin directory" cp --remove-destination "${TMP_DIR}/AIS-catcher/plugins/"* "$PLUGIN_DIR" || error_exit "Failed to copy plugins" log "INFO" "Installing DBMS" mkdir -p "$DBMS_DIR" || error_exit "Failed to create DBMS directory" cp --remove-destination "${TMP_DIR}/AIS-catcher/Source/DBMS/create_pg.sql" "${TMP_DIR}/AIS-catcher/Source/DBMS/create_sqlite.sql" "$DBMS_DIR" || error_exit "Failed to copy DBMS" log "INFO" "Installing README" mkdir -p "$README_DIR" || error_exit "Failed to create README directory" cp --remove-destination "${TMP_DIR}/AIS-catcher/README.md" "$README_DIR" || error_exit "Failed to copy README" log "INFO" "Copying LICENSE" cp --remove-destination "${TMP_DIR}/AIS-catcher/LICENSE" /etc/AIS-catcher/LICENSE || error_exit "Failed to copy LICENSE" } ################################################################################ # PACKAGE INSTALLATION FUNCTIONS ################################################################################ # Check if a pre-built package is available for this system # Args: # $1: system_info string (format: os_version_arch) # Returns: # 0 if package found (prints package name), 1 otherwise check_package_availability() { local system_info=$1 local packages=( "ais-catcher_debian_bookworm_amd64.deb" "ais-catcher_debian_bookworm_arm64.deb" "ais-catcher_debian_bookworm_armhf.deb" "ais-catcher_debian_trixie_amd64.deb" "ais-catcher_debian_trixie_arm64.deb" "ais-catcher_debian_trixie_armhf.deb" "ais-catcher_ubuntu_focal_amd64.deb" "ais-catcher_ubuntu_focal_arm64.deb" "ais-catcher_ubuntu_jammy_amd64.deb" "ais-catcher_ubuntu_jammy_arm64.deb" "ais-catcher_ubuntu_jammy_armhf.deb" "ais-catcher_ubuntu_noble_amd64.deb" "ais-catcher_ubuntu_noble_arm64.deb" "ais-catcher_ubuntu_noble_armhf.deb" "ais-catcher_ubuntu_plucky_amd64.deb" "ais-catcher_ubuntu_plucky_arm64.deb" "ais-catcher_ubuntu_plucky_armhf.deb" "ais-catcher_ubuntu_questing_amd64.deb" "ais-catcher_ubuntu_questing_arm64.deb" "ais-catcher_ubuntu_questing_armhf.deb" "ais-catcher_ubuntu_resolute_amd64.deb" "ais-catcher_ubuntu_resolute_arm64.deb" "ais-catcher_ubuntu_resolute_armhf.deb" "ais-catcher_fedora_43_x86_64.rpm" "ais-catcher_fedora_43_aarch64.rpm" "ais-catcher_fedora_44_x86_64.rpm" "ais-catcher_fedora_44_aarch64.rpm" ) for package in "${packages[@]}"; do if [[ $package == *"$system_info"* ]]; then echo "$package" return 0 fi done return 1 } # Download and install a pre-built package (.deb or .rpm) by filename. # Separated from install_package_method so the download/install logic can be # tested or reused independently of the method-selection layer. download_and_install_pkg() { local package=$1 local download_url="https://github.com/jvde-github/AIS-catcher/releases/download/Edge/$package" log "INFO" "Installing AIS-catcher from package: $package" # chmod 755 so apt's _apt sandbox user can read the .deb; global so the EXIT trap cleans it. DEB_TMP_DIR=$(mktemp -d) chmod 755 "$DEB_TMP_DIR" # Download the package and check it against its .sha256 on the release local attempt expected actual for attempt in 1 2; do log "INFO" "Downloading package..." if ! curl -fsL -o "$DEB_TMP_DIR/$package" "$download_url"; then rm -rf "$DEB_TMP_DIR"; DEB_TMP_DIR="" log "WARN" "Failed to download package" return 1 fi expected=$(curl -fsL "$download_url.sha256" 2>/dev/null | awk '{print $1}') || expected="" actual=$(sha256sum "$DEB_TMP_DIR/$package" | awk '{print $1}') if [ -z "$expected" ]; then log "WARN" "No checksum published for $package: installing it unverified" break elif [ "$expected" = "$actual" ]; then log "INFO" "Checksum verified (sha256 $actual)" break elif [ "$attempt" = 2 ]; then rm -rf "$DEB_TMP_DIR"; DEB_TMP_DIR="" log "WARN" "Checksum mismatch for $package: not installed" return 1 fi log "WARN" "Checksum mismatch for $package, the release may be updating: trying again in 30 seconds" sleep 30 done # Ensure the downloaded file has correct permissions chmod 644 "$DEB_TMP_DIR/$package" log "INFO" "Installing package and dependencies..." local install_success=false if [[ "$package" == *.rpm ]]; then if dnf -y install "$DEB_TMP_DIR/$package"; then install_success=true log "INFO" "Package installed successfully" fi else # Use --allow-downgrades to handle version conflicts and better error handling local apt_opts=(-y --allow-downgrades -o Dpkg::Options::=--force-confnew) if DEBIAN_FRONTEND=noninteractive apt-get install "${apt_opts[@]}" "$DEB_TMP_DIR/$package"; then install_success=true log "INFO" "Package installed successfully" else log "WARN" "Standard package installation failed, trying with additional flags..." if DEBIAN_FRONTEND=noninteractive apt-get install "${apt_opts[@]}" --allow-change-held-packages "$DEB_TMP_DIR/$package"; then install_success=true log "INFO" "Package installed successfully with additional flags" fi fi fi # Clean up temporary directory rm -rf "$DEB_TMP_DIR" || log "WARN" "Failed to remove temporary directory: $DEB_TMP_DIR" DEB_TMP_DIR="" if [[ "$install_success" != true ]]; then log "WARN" "Failed to install package after all attempts" return 1 fi log "INFO" "AIS-catcher package installation completed" } # Resolve which pre-built package to use for this system and drive download_and_install_pkg. install_package_method() { local system_info system_info=$(get_system_info) log "INFO" "Detected system: $system_info" # Declare separately so the assignment exit-code is not masked by 'local'. local package package=$(check_package_availability "$system_info") || true if [ -z "$package" ]; then log "WARN" "No pre-built package available for $system_info" return 1 fi log "INFO" "Package available: $package" # Install minimal dependencies for package installation (skip if curl is # already present — on Fedora, installing curl over curl-minimal conflicts) if ! command -v curl &>/dev/null; then log "INFO" "Installing minimal dependencies for package installation" pkg_install curl || error_exit "Failed to install minimal dependencies" fi download_and_install_pkg "$package" || return 1 log "INFO" "AIS-catcher installation from package completed successfully" } ################################################################################ # CONFIGURATION FUNCTIONS (Common to both installation methods) ################################################################################ # Create and configure aiscatcher system user setup_aiscatcher_user() { if [ "$SKIP_USER" = true ]; then log "INFO" "Skipping user creation (--no-user flag specified), will run as root" return 0 fi log "INFO" "Setting up aiscatcher system user" # Create system user if it doesn't exist if ! id -u aiscatcher &>/dev/null; then log "INFO" "Creating aiscatcher system user" useradd --system --no-create-home --shell /usr/sbin/nologin aiscatcher || error_exit "Failed to create aiscatcher user" else log "INFO" "User aiscatcher already exists" fi # Add user to necessary groups for SDR device access for group in plugdev dialout; do if getent group "$group" &>/dev/null; then if ! id -nG aiscatcher | grep -qw "$group"; then log "INFO" "Adding aiscatcher to $group group" usermod -a -G "$group" aiscatcher || log "WARN" "Failed to add aiscatcher to $group group" fi else log "WARN" "Group $group does not exist, skipping" fi done } # Setup configuration setup_configuration() { log "INFO" "Setting up configuration files" mkdir -p "$CONFIG_DIR" || error_exit "Failed to create config directory" if [[ "$MANAGED" == true ]]; then mkdir -p "$CONFIG_DIR/places" || error_exit "Failed to create places directory" chmod 750 "$CONFIG_DIR/places" fi # Managed mode on a machine with a pre-existing legacy config: seed the # managed config with its path so the setup wizard can offer to import # the configured output channels. Must run before the legacy default # config is (re)created below, so a fresh install does not qualify. # A link counts as there: this runs as root in a folder the service's user owns. if [[ "$MANAGED" == true && ! -f "$MANAGED_CONFIG_FILE" && ! -L "$MANAGED_CONFIG_FILE" && -f "$CONFIG_FILE" ]]; then log "INFO" "Existing config.json found; the setup wizard will offer to import its outputs" # a station that said no to sharing stays that way local seed_sharing=true if grep -qsE '"sharing"[[:space:]]*:[[:space:]]*(false|"off")' "$CONFIG_FILE" || grep -qsE '(^|[[:space:]])-X[[:space:]]+off' "$CMD_FILE"; then seed_sharing=false fi cat << EOF | tee "$MANAGED_CONFIG_FILE" > /dev/null || error_exit "Failed to create aiscatcher.json" { "config": "aiscatcher", "version": 1, "engine": "off", "sharing": ${seed_sharing}, "control": { "wizard": true, "legacy_config": "${CONFIG_FILE}" } } EOF fi if [[ ! -f "$CONFIG_FILE" && ! -L "$CONFIG_FILE" ]]; then echo '{"config":"aiscatcher","version":1,"screen":0,"verbose":true,"verbose_time":60,"sharing":true,"udp":[],"tcp":[],"server":{"active":false,"plugin_dir":"/etc/AIS-catcher/plugins","cdn":"/etc/AIS-catcher/webassets","file":"/etc/AIS-catcher/stat.bin","realtime":false,"geojson":false,"prome":false,"port":"8100","backup":"10","context":"settings"},"rtlsdr":{"tuner":"auto","bandwidth":"192K","sample_rate":"1536K","biastee":false,"rtlagc":true},"airspyhf":{"threshold":"low","preamp":false},"rtltcp":{"protocol":"none","sample_rate":"288K","bandwidth":"0","rtlagc":false}}' | tee "$CONFIG_FILE" > /dev/null || error_exit "Failed to create config.json" fi if [[ ! -f "$CMD_FILE" && ! -L "$CMD_FILE" ]]; then cat << EOF | tee "$CMD_FILE" > /dev/null || error_exit "Failed to create config.cmd" # AIS-catcher configuration EOF fi } ################################################################################ # SYSTEMD SERVICE FUNCTIONS (Common to both installation methods) ################################################################################ # Install the reboot watchdog poll script install_reboot_script() { local script_path="${LIB_DIR}/wait-and-reboot.sh" mkdir -p "$LIB_DIR" || error_exit "Failed to create lib directory" cat > "$script_path" << 'SCRIPT' #!/bin/bash # Schedule a reboot in 5 minutes; cancel it if AIS-catcher recovers in time. # Checks every 10 seconds; cancels the pending shutdown if the service comes # back active (e.g. after manual "systemctl reset-failed + start" intervention). # To cancel a pending reboot manually: shutdown -c REBOOT_MINUTES=5 shutdown -r "+${REBOOT_MINUTES}" "AIS-catcher failed repeatedly - rebooting in ${REBOOT_MINUTES} minutes. To cancel: shutdown -c" for i in $(seq 30); do sleep 10 if systemctl is-active --quiet ais-catcher.service; then shutdown -c exit 0 fi done SCRIPT chmod 755 "$script_path" || error_exit "Failed to set permissions on reboot script" log "INFO" "Reboot watchdog script installed to ${script_path}" } # Setup systemd service # A hardening line, unless a configuration names a path it would hide or freeze: that line stays off # with a warning, as a station that ran with such a path must not lose it on an upgrade hardening_line() { local line=$1 pattern=$2 if grep -qsE "$pattern" "$CONFIG_FILE" "$CMD_FILE" "$MANAGED_CONFIG_FILE"; then log "WARN" "${line} left out of the service: the configuration names a path it would hide or freeze" >&2 else echo "$line" fi } setup_systemd_service() { log "INFO" "Setting up systemd service" install_reboot_script # Write the reboot watchdog unit — fires only when OnFailure is triggered (StartLimitBurst > 0) # Type=simple: systemd spawns the script and does not wait for it to exit, which avoids # hitting TimeoutStartSec (90s default) during the 5-minute cancellation window. cat > "$REBOOT_SERVICE_FILE" << EOF [Unit] Description=Reboot system due to repeated AIS-catcher failures [Service] Type=simple ExecStart=${LIB_DIR}/wait-and-reboot.sh EOF log "INFO" "Reboot watchdog service written to ${REBOOT_SERVICE_FILE}" # Preserve existing burst/interval/restart from current service file if present local burst=0 local interval=0 local restart_policy="always" if [[ -f "$SERVICE_FILE" ]]; then burst=$(grep "^StartLimitBurst=" "$SERVICE_FILE" | cut -d= -f2 || echo 0) interval=$(grep "^StartLimitIntervalSec=" "$SERVICE_FILE" | cut -d= -f2 || echo 0) local existing_restart existing_restart=$(grep "^Restart=" "$SERVICE_FILE" | cut -d= -f2 || true) burst=${burst:-0} interval=${interval:-0} [[ "$burst" =~ ^[0-9]+$ ]] || burst=0 [[ "$interval" =~ ^[0-9]+$ ]] || interval=0 restart_policy=${existing_restart:-always} log "INFO" "Preserving existing service limits: burst=${burst} interval=${interval}s restart=${restart_policy}" fi # Apply explicitly requested toggle overrides when combined with an installation if [[ "$SET_REBOOT" == "true" ]]; then burst="$REBOOT_BURST" interval="$REBOOT_INTERVAL" log "INFO" "Overriding watchdog settings: burst=${burst} interval=${interval}s" elif [[ "$SET_REBOOT" == "false" ]]; then burst=0 interval=0 log "INFO" "Disabling watchdog as requested" fi if [[ "$SET_AUTO_RESTART" == "true" ]]; then restart_policy="always" log "INFO" "Overriding auto-restart: always" elif [[ "$SET_AUTO_RESTART" == "false" ]]; then restart_policy="no" log "INFO" "Disabling auto-restart as requested" fi # Build main service file content # OnFailure= is only meaningful when StartLimitBurst > 0; with burst=0 the service # restarts indefinitely via Restart=always and OnFailure would fire on every crash. local on_failure_line="" if [[ "${burst}" -gt 0 ]]; then on_failure_line="OnFailure=${REBOOT_SERVICE_NAME}" fi local service_content="[Unit] Description=AIS-catcher Service After=network.target ${on_failure_line:+${on_failure_line}$'\n'}StartLimitIntervalSec=${interval} StartLimitBurst=${burst} [Service]" # Only add User/Group directives if not skipping user creation if [ "$SKIP_USER" = false ]; then service_content+=" User=aiscatcher Group=aiscatcher SupplementaryGroups=plugdev dialout" fi local exec_start="/usr/bin/AIS-catcher -G level debug -o 0 -C ${CONFIG_FILE} @${CMD_FILE}" if [ "$MANAGED" = true ]; then exec_start="/usr/bin/AIS-catcher -E ${MANAGED_CONFIG_FILE} ${MANAGED_BIND}" fi local hardening hardening=$(hardening_line "PrivateTmp=true" "[\"' =,]/(var/)?tmp/" hardening_line "ProtectHome=true" "[\"' =,]/(home|root)/" hardening_line "ProtectSystem=true" "(FILE|file)[\"[:space:]:]+/(usr|boot)/") service_content+=" ExecStart=${exec_start} Restart=${restart_policy} RestartSec=10 NoNewPrivileges=true ${hardening} [Install] WantedBy=multi-user.target" echo "$service_content" | tee "$SERVICE_FILE" > /dev/null || error_exit "Failed to create service file" systemctl daemon-reload || error_exit "Failed to reload systemd" } # Function to stop the service and save its state stop_disable_and_save_service_state() { log "INFO" "Checking AIS-catcher service state, stopping if active, and disabling" local was_active=false local was_enabled=false # Check if the service is active if systemctl is-active --quiet "$SERVICE_NAME"; then was_active=true log "INFO" "$SERVICE_NAME is active, attempting to stop" if systemctl stop "$SERVICE_NAME"; then log "INFO" "$SERVICE_NAME stopped successfully" else log "WARN" "Failed to stop $SERVICE_NAME" fi elif systemctl is-failed --quiet "$SERVICE_NAME" 2>/dev/null; then # Service is in a failed/crash-loop state — it was intended to be running was_active=true log "INFO" "$SERVICE_NAME is in failed state, resetting before update" systemctl reset-failed "$SERVICE_NAME" || log "WARN" "Failed to reset failed state" else log "INFO" "$SERVICE_NAME is not active, no need to stop" fi # Check if the service is enabled if systemctl is-enabled --quiet "$SERVICE_NAME"; then was_enabled=true log "INFO" "$SERVICE_NAME is enabled, attempting to disable" if systemctl disable "$SERVICE_NAME"; then log "INFO" "$SERVICE_NAME disabled successfully" else log "WARN" "Failed to disable $SERVICE_NAME" fi else log "INFO" "$SERVICE_NAME is not enabled, no need to disable" fi # Save the state to the global variable SERVICE_STATE="${was_active},${was_enabled}" log "INFO" "Service state saved: $SERVICE_STATE" } # A start command can succeed while the process then exits (most commonly # because its ports are already in use), so poll is-active and dump diagnostics # if the service never comes up. Returns non-zero if it does not. verify_service_active() { local started=false i for i in {1..10}; do systemctl is-active --quiet "$SERVICE_NAME" && { started=true; break; } sleep 1 done if [[ "$started" == true ]]; then log "INFO" "$SERVICE_NAME is running properly" return 0 fi log "ERROR" "$SERVICE_NAME did not stay running after start" systemctl status "$SERVICE_NAME" --no-pager -l 2>/dev/null | tail -n 15 || true journalctl -u "$SERVICE_NAME" -n 20 --no-pager 2>/dev/null || true if [[ "$MANAGED" == true ]]; then local ctrl_port="${MANAGED_BIND##*:}" log "ERROR" "Managed mode could not start — control port ${ctrl_port} or viewer port $((ctrl_port + 1)) may already be in use" log "ERROR" "Free the port(s), then run: systemctl restart ${SERVICE_NAME}" fi return 1 } # FIXED: Improved service state restoration with better error handling restore_service_state() { if [[ -z "$SERVICE_STATE" ]]; then log "INFO" "No service state to restore" return 0 fi log "INFO" "Restoring AIS-catcher service state" IFS=',' read -ra STATE_ARRAY <<< "$SERVICE_STATE" local was_active=${STATE_ARRAY[0]:-false} local was_enabled=${STATE_ARRAY[1]:-false} # Enable first if it was enabled if [[ "$was_enabled" == true ]]; then if systemctl enable "$SERVICE_NAME"; then log "INFO" "$SERVICE_NAME enabled successfully" else log "ERROR" "Failed to enable $SERVICE_NAME" return 1 fi fi # Then start if it was active if [[ "$was_active" == true ]]; then # Clear any stale failed state from before the update so start isn't blocked systemctl reset-failed "$SERVICE_NAME" 2>/dev/null || true if systemctl start "$SERVICE_NAME"; then log "INFO" "$SERVICE_NAME start command issued" # Only verify the managed default-start (the script's own decision); # a plain restore of the user's prior state is taken at face value. if [[ "$MANAGED" == true ]]; then verify_service_active || SERVICE_START_FAILED=true fi else log "ERROR" "Failed to start $SERVICE_NAME" return 1 fi fi # Clear the global state after restore SERVICE_STATE="" log "INFO" "Service state restored and cleared" return 0 } ################################################################################ # INSTALLATION METHOD FUNCTIONS ################################################################################ # Parse command-line arguments parse_arguments() { while [[ $# -gt 0 ]]; do case "$1" in -p|--package) log "INFO" "Package installation requested" INSTALL_PACKAGE=true INSTALL_REQUESTED=true shift ;; -i|--interactive) log "INFO" "Interactive feature selection requested (forces source build)" INTERACTIVE=true INSTALL_REQUESTED=true shift ;; -b|--branch) if [[ -n "${2:-}" && "${2:0:1}" != "-" ]]; then BRANCH="$2" INSTALL_REQUESTED=true log "INFO" "Will clone branch: ${BRANCH}" shift 2 else error_exit "Option -b/--branch requires a branch name argument" fi ;; -M|--managed) log "INFO" "Managed mode service requested (-E ${MANAGED_CONFIG_FILE} ${MANAGED_BIND})" MANAGED=true INSTALL_REQUESTED=true shift ;; --no-systemd) log "INFO" "Skipping systemd service installation" SKIP_SYSTEMD=true shift ;; --no-user) log "INFO" "Skipping user creation, will run as root" SKIP_USER=true shift ;; --set-reboot-on-failure) SET_REBOOT="true" if [[ -n "${2:-}" && "${2}" =~ ^[0-9]+$ ]]; then REBOOT_BURST="$2" shift fi if [[ -n "${2:-}" && "${2}" =~ ^[0-9]+$ ]]; then REBOOT_INTERVAL="$2" shift fi shift ;; --unset-reboot-on-failure) SET_REBOOT="false" shift ;; --set-auto-restart) SET_AUTO_RESTART="true" shift ;; --unset-auto-restart) SET_AUTO_RESTART="false" shift ;; -h|--help) usage ;; _) # old AIS-catcher-control builds invoke this script as "bash -s -- _ -p" shift ;; *) log "ERROR" "Unknown option: $1" log "INFO" "Use --help for usage information" exit 1 ;; esac done # Warn if --branch is ignored because --package was also specified if [[ "$INSTALL_PACKAGE" == true && "$BRANCH" != "main" ]]; then log "WARN" "--branch is ignored when --package is used (pre-built packages are always Edge)" fi # --interactive only makes sense for source builds; the .deb is pre-baked. if [[ "$INTERACTIVE" == true && "$INSTALL_PACKAGE" == true ]]; then log "WARN" "--interactive overrides --package (pre-built packages can't be customised)" INSTALL_PACKAGE=false fi } # Install from source install_from_source_method() { log "INFO" "AIS-catcher installation from source" cd "$TMP_DIR" || error_exit "Failed to change to temporary directory" install_source_build_dependencies install_sdr_libraries_from_source build_ais_catcher_from_source install_source_additional_files log "INFO" "AIS-catcher source installation completed successfully" } # Install binary (delegates to package or source method, with source fallback) install_binary() { if [ "$INSTALL_PACKAGE" = true ]; then if install_package_method; then return 0 fi log "WARN" "Package installation failed, falling back to source build..." fi install_from_source_method } # Configure installation (user, config, permissions) configure_installation() { setup_aiscatcher_user setup_configuration # Ensure correct ownership after config files are created (skip if running as root) if [ "$SKIP_USER" = false ]; then log "INFO" "Ensuring correct ownership of configuration directory" chown -R aiscatcher:aiscatcher "$CONFIG_DIR" || log "WARN" "Failed to set ownership of config directory" fi # The configuration holds the password's hash and the outputs' credentials. # find -type f: chmod would follow a link the service's user left here. chmod 750 "$CONFIG_DIR" || log "WARN" "Failed to set permissions of config directory" find "$CONFIG_DIR" -maxdepth 1 -type f \( -name config.json -o -name config.cmd -o -name aiscatcher.json \) \ -exec chmod 640 {} + || log "WARN" "Failed to set permissions of config files" } # Display installation summary with useful information display_installation_summary() { local divider="═══════════════════════════════════════════════════════════════════════════════" echo -e "\n${COLOR_BOLD_BLUE}${divider}${COLOR_RESET}" echo -e "${COLOR_BOLD_GREEN} AIS-CATCHER INSTALLATION SUMMARY${COLOR_RESET}" echo -e "${COLOR_BOLD_BLUE}${divider}${COLOR_RESET}\n" echo -e "${COLOR_BOLD_GREEN}✓ Installation completed successfully!${COLOR_RESET}\n" if [ "$SKIP_SYSTEMD" = false ]; then echo -e "${COLOR_BOLD}SERVICE STATUS:${COLOR_RESET}" if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then echo -e " • ${SERVICE_NAME}: ${COLOR_BOLD_GREEN}running${COLOR_RESET}" else echo -e " • ${SERVICE_NAME}: ${COLOR_YELLOW}not running${COLOR_RESET}" fi if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then echo -e " • Start on boot: ${COLOR_BOLD_GREEN}enabled${COLOR_RESET}" else echo -e " • Start on boot: ${COLOR_YELLOW}disabled${COLOR_RESET}" fi if [ "$SERVICE_START_FAILED" = true ]; then echo "" echo -e " ${COLOR_YELLOW}⚠ The service was started but did not stay running.${COLOR_RESET}" if [ "$MANAGED" = true ]; then local status_port="${MANAGED_BIND##*:}" echo -e " Control port ${status_port} or viewer port $((status_port + 1)) may already be in use." fi echo -e " Check logs: ${COLOR_YELLOW}journalctl -u ${SERVICE_NAME} -n 30 --no-pager${COLOR_RESET}" echo -e " Then retry: ${COLOR_YELLOW}systemctl restart ${SERVICE_NAME}${COLOR_RESET}" fi echo "" fi echo -e "${COLOR_BOLD}INSTALLED FILES:${COLOR_RESET}" echo " • Executable: /usr/bin/AIS-catcher" echo " • Configuration: ${CONFIG_DIR}/" echo " - Main config: ${CONFIG_FILE}" echo " - Command options: ${CMD_FILE}" echo " - Plugins: ${PLUGIN_DIR}/" echo " - Database schema: ${DBMS_DIR}/create_pg.sql, ${DBMS_DIR}/create_sqlite.sql" echo " - Documentation: ${README_DIR}/README.md" echo " - License: ${CONFIG_DIR}/LICENSE" if [ "$SKIP_SYSTEMD" = false ]; then echo " • Service file: ${SERVICE_FILE}" echo " • Reboot watchdog: ${REBOOT_SERVICE_FILE}" echo " • Reboot script: ${LIB_DIR}/wait-and-reboot.sh" fi echo " • Log file: ${LOG_FILE}" echo "" if [ "$SKIP_SYSTEMD" = false ]; then echo -e "${COLOR_BOLD}REBOOT WATCHDOG:${COLOR_RESET}" echo " • Off by default — service restarts indefinitely without rebooting" echo " • When armed: reboots after N rapid restarts within a time window" echo " • Useful for recovering from unresolvable USB device failures" echo " • Re-run this script to toggle (no reinstall needed):" echo -e " ${COLOR_YELLOW}sudo $SCRIPT_NAME --set-reboot-on-failure${COLOR_RESET} # 3 restarts in 30 min" echo -e " ${COLOR_YELLOW}sudo $SCRIPT_NAME --set-reboot-on-failure 5 3600${COLOR_RESET} # 5 restarts in 60 min" echo -e " ${COLOR_YELLOW}sudo $SCRIPT_NAME --unset-reboot-on-failure${COLOR_RESET} # disable" echo " • Settings stored directly in the service file: ${SERVICE_FILE}" echo "" echo -e "${COLOR_BOLD}AUTO-RESTART:${COLOR_RESET}" echo " • On by default — service restarts automatically after any crash (Restart=always)" echo " • Disable to prevent restart loops during troubleshooting" echo " • Re-run this script to toggle (no reinstall needed):" echo -e " ${COLOR_YELLOW}sudo $SCRIPT_NAME --set-auto-restart${COLOR_RESET} # enable Restart=always" echo -e " ${COLOR_YELLOW}sudo $SCRIPT_NAME --unset-auto-restart${COLOR_RESET} # disable Restart=no" echo " • If service locks up after failures, recover with:" echo -e " ${COLOR_YELLOW}systemctl reset-failed ${SERVICE_NAME} && systemctl start ${SERVICE_NAME}${COLOR_RESET}" echo " • To abort a pending reboot (during the 5-minute wait):" echo -e " ${COLOR_YELLOW}shutdown -c${COLOR_RESET}" echo "" fi if [ "$SKIP_SYSTEMD" = false ]; then echo -e "${COLOR_BOLD}SYSTEMD SERVICE MANAGEMENT:${COLOR_RESET}" echo " • View service status:" echo -e " ${COLOR_YELLOW}systemctl status ${SERVICE_NAME}${COLOR_RESET}" echo "" echo " • Start the service:" echo -e " ${COLOR_YELLOW}systemctl start ${SERVICE_NAME}${COLOR_RESET}" echo "" echo " • Stop the service:" echo -e " ${COLOR_YELLOW}systemctl stop ${SERVICE_NAME}${COLOR_RESET}" echo "" echo " • Restart the service:" echo -e " ${COLOR_YELLOW}systemctl restart ${SERVICE_NAME}${COLOR_RESET}" echo "" echo " • Enable at boot:" echo -e " ${COLOR_YELLOW}systemctl enable ${SERVICE_NAME}${COLOR_RESET}" echo "" echo " • Disable at boot:" echo -e " ${COLOR_YELLOW}systemctl disable ${SERVICE_NAME}${COLOR_RESET}" echo "" echo " • View service logs:" echo -e " ${COLOR_YELLOW}journalctl -u ${SERVICE_NAME} -f${COLOR_RESET}" echo "" fi echo -e "${COLOR_BOLD}CONFIGURATION:${COLOR_RESET}" if [ "$MANAGED" = true ]; then echo " • Managed mode: configure everything from the hub, not by hand" echo -e " config file: ${COLOR_YELLOW}${MANAGED_CONFIG_FILE}${COLOR_RESET}" echo "" echo " • The engine starts, stops and restarts from the hub" else echo " • Edit main configuration:" echo -e " ${COLOR_YELLOW}nano ${CONFIG_FILE}${COLOR_RESET}" echo "" echo " • Edit command-line options:" echo -e " ${COLOR_YELLOW}nano ${CMD_FILE}${COLOR_RESET}" echo "" echo " • After editing, restart the service:" echo -e " ${COLOR_YELLOW}systemctl restart ${SERVICE_NAME}${COLOR_RESET}" if grep -qsE '"sharing"[[:space:]]*:[[:space:]]*true' "$CONFIG_FILE" && ! grep -qsE '(^|[[:space:]])-X[[:space:]]+off' "$CMD_FILE"; then echo "" echo " • Community sharing is on: what this station receives is sent to aiscatcher.org" echo -e " To turn it off, set ${COLOR_YELLOW}\"sharing\": false${COLOR_RESET} in ${CONFIG_FILE}" fi fi echo "" echo -e "${COLOR_BOLD}WEB INTERFACE:${COLOR_RESET}" if [ "$MANAGED" = true ]; then local ctrl_port="${MANAGED_BIND##*:}" echo " • Control hub (configuration and control):" echo -e " ${COLOR_CYAN}http://localhost:${ctrl_port}${COLOR_RESET}" echo " • Built-in map viewer:" echo -e " ${COLOR_CYAN}http://localhost:$((ctrl_port + 1))${COLOR_RESET}" echo " (or use your server's IP address)" echo "" echo " • Set an admin password on your first visit. The page asks for a setup code," echo " which only the log shows:" echo -e " ${COLOR_YELLOW}journalctl -u ${SERVICE_NAME} | grep 'setup code'${COLOR_RESET}" local setup_code="" for _ in 1 2 3 4 5; do setup_code=$(sed -n 's/.*"setup_code" *: *"\([^"]*\)".*/\1/p' "$MANAGED_CONFIG_FILE" 2>/dev/null || true) [ -n "$setup_code" ] && break grep -q '"password"' "$MANAGED_CONFIG_FILE" 2>/dev/null && break sleep 1 done if [ -n "$setup_code" ]; then echo -e " Setup code now: ${COLOR_YELLOW}${setup_code}${COLOR_RESET}" fi else echo " • Once running, access the web interface at:" echo -e " ${COLOR_CYAN}http://localhost:8100${COLOR_RESET}" echo " (or use your server's IP address)" echo "" echo " • Enable the web server by editing ${CONFIG_FILE}" echo -e " and setting ${COLOR_YELLOW}\"active\": true${COLOR_RESET} in the \"server\" section" fi echo "" echo -e "${COLOR_BOLD}USEFUL COMMANDS:${COLOR_RESET}" echo " • Run AIS-catcher directly (for testing):" echo -e " ${COLOR_YELLOW}AIS-catcher -h${COLOR_RESET}" echo "" echo " • View this installation log:" echo -e " ${COLOR_YELLOW}cat ${LOG_FILE}${COLOR_RESET}" echo "" echo -e "${COLOR_BOLD}DOCUMENTATION:${COLOR_RESET}" echo -e " • Online docs: ${COLOR_CYAN}https://docs.aiscatcher.org/${COLOR_RESET}" echo -e " • GitHub repo: ${COLOR_CYAN}https://github.com/jvde-github/AIS-catcher${COLOR_RESET}" echo " • Local README: ${README_DIR}/README.md" echo "" echo -e "${COLOR_BOLD_BLUE}${divider}${COLOR_RESET}\n" } # Main function main() { require_root "$@" # Phase 1: Logging, temp dir, and cleanup trap log "INFO" "Starting AIS-catcher installation script" TMP_DIR=$(mktemp -d -t AIS-catcher-XXXXXX) readonly TMP_DIR trap cleanup EXIT # Phase 2: Parse arguments first — ensures --help exits cleanly and standalone # toggle flags don't hit the installation pre-flight checks unnecessarily. parse_arguments "$@" # Phase 3: Cancel any pending watchdog — must happen before any service state change, # whether we're on the standalone-toggle path or the full-install path. if [ "$SKIP_SYSTEMD" = false ]; then cancel_reboot_watchdog fi # Phase 4: Handle standalone toggles (no reinstall needed). # If -p or -b was also passed (INSTALL_REQUESTED=true), skip early-exit and let # setup_systemd_service() apply the overrides inline during the installation instead. if [[ -n "$SET_REBOOT" && "$INSTALL_REQUESTED" == "false" ]]; then handle_reboot_setting exit 0 fi if [[ -n "$SET_AUTO_RESTART" && "$INSTALL_REQUESTED" == "false" ]]; then handle_auto_restart_setting exit 0 fi # Phase 4b: Interactive feature selection (drives apt deps, source-lib clones, cmake flags) if [[ "$INTERACTIVE" == true ]]; then interactive_feature_select fi # Phase 5: Pre-flight checks (only reached for actual installations) check_existing_service # Phase 6: System preparation require_package_manager pkg_update || error_exit "Failed to update package lists" # Phase 7: Stop existing service if needed if [ "$SKIP_SYSTEMD" = false ]; then stop_disable_and_save_service_state fi # Phase 8: Install binary (package or source) install_binary [[ -x /usr/bin/AIS-catcher ]] || error_exit "AIS-catcher binary not found after installation" # Phase 9: Post-install configuration configure_installation # Phase 10: Setup and start service if [ "$SKIP_SYSTEMD" = false ]; then setup_systemd_service # Managed installs (-M) are enabled and started by default, regardless of prior state. if [ "$MANAGED" = true ]; then log "INFO" "Managed mode: enabling and starting ${SERVICE_NAME} by default" SERVICE_STATE="true,true" fi if ! restore_service_state; then log "ERROR" "Failed to restore service state" exit 1 fi else log "INFO" "Skipping systemd service installation (--no-systemd flag specified)" fi # Phase 11: Installation complete log "INFO" "AIS-catcher installation completed successfully" display_installation_summary } # Run the script main "$@"