#!/bin/bash
# script updated Nov-06-2026 on github or http://f6bvp.org
# Copy this script file in /usr/local/src/ax25/ (updfpac = stable FPAC, updfpac-rc = release candidates)
# and execute command : sudo chmod a+x updfpac
# execute command to run the script : sudo ./updfpac
# It will update, compile and install FPAC AX.25 ROSE application
#
# The FPAC version is no longer written in this script: it is the newest tag
# published on GitHub (ve7fet/fpac and f6bvp/fpac) whose signed source package
# is available on f6bvp.org.
#   CANAL=stable : newest release (no -rc tag), e.g. 4.1.5, then 4.2 ...
#   CANAL=rc     : newest tag including release candidates (a final release
#                  comes after its own candidates : 4.2-rc3 < 4.2)
# Options : --essai  only shows which version would be installed
#           --force  allows going back to an older version than the installed one

CANAL=stable
# Used only when GitHub cannot be reached
VERSION_SECOURS=4.1.5

SRCDIR=/usr/local/src/ax25
EXTENT=tar.xz
# Color Codes
Reset='\e[0m'
Red='\e[31m'
Green='\e[30;42m'  # Black/Green
Yellow='\e[33m'
YelRed='\e[31;43m' #Red/Yellow
YelGreen='\e[31;42m' #Red/Green
Blue='\e[34m'
White='\e[37m'
BluW='\e[37;44m'

# --- Verification d'authenticite minisign ------------------------------------
# Cle PUBLIQUE livree une fois sur chaque machine (jamais telechargee).
PUBKEY=/usr/local/etc/ax25/f6bvp-minisign.pub
#
# fetch_verified URL : telecharge le fichier ET sa signature .minisig dans le
# repertoire courant, puis verifie la signature avec la cle publique.
# Renvoie 0 si tout est bon, sinon supprime les fichiers douteux et renvoie 1.
fetch_verified() {
    local url="$1" base
    base=$(basename "$url")
    rm -f "$base" "$base.minisig"
    if ! wget -q "$url" || ! wget -q "$url.minisig" ; then
        echo -e "${Red}\t Telechargement echoue : $base ${Reset}" >&2
        rm -f "$base" "$base.minisig"
        return 1
    fi
    if ! minisign -Vqm "$base" -p "$PUBKEY" ; then
        echo -e "${Red}\t SIGNATURE INVALIDE : $base -- fichier rejete ${Reset}" >&2
        rm -f "$base" "$base.minisig"
        return 1
    fi
    return 0
}
# -----------------------------------------------------------------------------



if [ "$(id -u)" != "0" ]; then
        echo "You must be root to execute this script !"
        exit 1
fi

if [ ! -f "$PUBKEY" ]; then
        echo -e "${Red}\t Cle publique minisign absente : $PUBKEY ${Reset}"
        echo -e "${Red}\t Impossible de verifier les telechargements -- abandon. ${Reset}"
        exit 1
fi


# --- Choice of the FPAC version ---------------------------------------------
# Tags of the GitHub repositories, newest first ; a final release is sorted
# after its own release candidates.
versions_publiees() {
    local r
    for r in ve7fet/fpac f6bvp/fpac ; do
        wget -q -O - "https://api.github.com/repos/$r/tags?per_page=100"
    done | grep -o '"name": *"v[0-9][0-9.]*\(-rc[0-9]*\)\?"' \
         | sed 's/.*"v\(.*\)"/\1/' | sort -u \
         | { if [ "$CANAL" = "stable" ] ; then grep -v -- '-rc' ; else cat ; fi ; } \
         | sed '/-rc/!s/$/-zz/' | sort -rV | sed 's/-zz$//'
}
VERSION=""
for v in $(versions_publiees | head -5) ; do
    # only a version whose signed package is on f6bvp.org
    if wget -q --spider "http://f6bvp.org/fpac-$v.$EXTENT" && \
       wget -q --spider "http://f6bvp.org/fpac-$v.$EXTENT.minisig" ; then
        VERSION=$v
        break
    fi
    echo -e "${Yellow}\t Tag v$v found on GitHub but fpac-$v.$EXTENT not yet on f6bvp.org${Reset}"
done
if [ -z "$VERSION" ] ; then
    VERSION=$VERSION_SECOURS
    echo -e "${Yellow}\t GitHub tags not available -- using version $VERSION${Reset}"
fi
FPAC=fpac-$VERSION
FPACDIR=$SRCDIR/$FPAC
VERS=$FPAC.$EXTENT
echo -e "${Green}\t FPAC version to install ($CANAL) : $VERSION ${Reset}"
INSTALLEE=""
if [ -x /usr/local/sbin/fpacnode ] ; then
    INSTALLEE=$(strings /usr/local/sbin/fpacnode | grep -m1 -oE '^[0-9]+\.[0-9]+(\.[0-9]+)?(-rc[0-9]+)?$')
    echo -e "\t  * Installed : ${INSTALLEE:-unknown}"
fi
# Never go back to an older version without being asked (--force)
if [ -n "$INSTALLEE" ] && [ "$INSTALLEE" != "$VERSION" ] && [ "$1" != "--force" ] ; then
    PLUS_RECENTE=$(printf '%s\n%s\n' "$INSTALLEE" "$VERSION" | sed '/-rc/!s/$/-zz/' | sort -V | tail -1 | sed 's/-zz$//')
    if [ "$PLUS_RECENTE" = "$INSTALLEE" ] ; then
        echo -e "${Red}\t Installed FPAC $INSTALLEE is NEWER than $VERSION : nothing done.${Reset}"
        echo -e "${Red}\t To go back to $VERSION anyway : sudo ./$(basename "$0") --force${Reset}"
        exit 1
    fi
fi
if [ "$1" = "--essai" ] ; then
    echo -e "${Yellow}\t Test only (--essai) : nothing downloaded, compiled or installed.${Reset}"
    exit 0
fi
# -----------------------------------------------------------------------------

echo -e "${BluW}\t\n\t Script provided by Charles S. Schuman modified by F6BVP for updating FPAC package\t\n\t\t\t ${Red} Nov-06-2026    \n \t\t${Yellow}       k4gbb1@gmail.com bernard.f6bvp@gmail.com \n${Reset}"

if [ ! -d "${SRCDIR}" ] ; then
    mkdir ${SRCDIR}
fi

if [ -f $FPACDIR/fpacerror.txt ] ; then
  rm -f $FPACDIR/fpacerror.txt
fi
if [ -f $FPACDIR/liberror.txt ] ; then
  rm -f $FPACDIR/liberror.txt
fi
# Update fpac source file package already present ?
if [ -d $FPACDIR/.git ] ; then
  echo -e "${Red}\t Updating $FPAC source files from repository ${Reset}"
  cd $FPACDIR
#  git pull
else
# Existing version package was not an fpac clone - remove it
  if [ -d $FPACDIR ] ; then
    rm -fr $FPACDIR
  fi
  echo -e "${Red}\t Getting FPAC version $VERS source files from repository${Reset}"
  cd $SRCDIR
# Remove old zip files
if [ -f ${VERS} ] ; then
echo -e "\n\t${Green} Deleting old file $VERS ${Reset}"
/bin/rm -f ${VERS}
fi
#
# Download last updated myfpac.sh script (signature minisign verifiee)
if fetch_verified http://f6bvp.org/myfpac.sh ; then
  install -m 755 myfpac.sh /usr/local/sbin/myfpac.sh
  ln -sf /usr/local/sbin/myfpac.sh /usr/local/etc/ax25/myfpac.sh
  rm -f myfpac.sh myfpac.sh.minisig
else
  echo -e "${Red}\t MAJ myfpac.sh refusee -- version locale conservee ${Reset}"
fi
#
# Download fpac source file package (signature minisign verifiee)
if ! fetch_verified http://f6bvp.org/${VERS} ; then
  echo -e "${Red}\t ${VERS} indisponible ou signature invalide -- abandon ${Reset}"
  exit 1
fi
#
# --no-same-owner : la tarball porte l'uid numerique du poste de fabrication
# (1000). Extraite en root sur un site distant, tar restaurerait cet uid, qui
# y designe un AUTRE utilisateur -- le ./configure lance plus bas en
# "sudo -u $SUDO_USER" ne pourrait alors pas ecrire config.log.
tar --no-same-owner -xf ${VERS}
chown -R "${SUDO_USER:-$(id -un)}" "$FPACDIR"
#
  echo -e "${Green}\t Be patient while running 'autoreconf' and 'configure' to create Makefile(s)${Reset}"
  cd $FPACDIR
  if [ -x ./autogen.sh ] ; then
    sudo -u "${SUDO_USER:-$(id -un)}" ./autogen.sh
  fi
  sudo -u "${SUDO_USER:-$(id -un)}" ./configure > fpac_error.txt 2>&1
  echo -e -n "\t  *"
fi
# Makefile ready ?
if [ ! -f $FPACDIR/Makefile ] ; then
  echo -e "${Green}\t Be patient while running 'autoreconf' and 'configure' to create Makefile(s)${Reset}"
  cd $FPACDIR
  if [ -x ./autogen.sh ] ; then
    sudo -u "${SUDO_USER:-$(id -un)}" ./autogen.sh
  fi
  sudo -u "${SUDO_USER:-$(id -un)}" ./configure >> fpac_error.txt 2>&1
  echo -e -n "\t  *"
fi
# Compile (as the invoking user, so build artifacts are not owned by root)
  echo -e "${Green}\t Compiling FPAC will take a while !${Reset}"
  sudo -u "${SUDO_USER:-$(id -un)}" make -s -j4 >> fpac_error.txt 2>&1
  if [ $? -ne 0 ]
    then
     echo -e "${Red}\t FPAC Compile error - See fpac_error.txt ${Reset}"
     exit 1
  fi
# Install (as root, writes into /usr/local)
  make -s -j4 install >> fpac_error.txt 2>&1
  if [ $? -ne 0 ]
   then
     echo -e "${Red} FPAC Install error - See fpac_error.txt${Reset}"
     exit 1
   else
     echo -e "${Green}\t FPAC Installed${Reset}"
  fi
if [ -f $FPACDIR/fpac_error.txt ] ; then
  rm -f $FPACDIR/fpac_error.txt
fi
if [ -f $FPACDIR/liberror.txt ] ; then
  rm -f $FPACDIR/liberror.txt
fi

# Set permissions for /usr/local/sbin/ and /usr/local/bin
  cd /usr/local/sbin/
  chmod 775 *
  cd /usr/local/bin/
  chmod 775 *
  echo -e "${Green}\t Fpac successfully rebuilt and installed !${Reset}\n"
  echo -e "${Green}\t If this is a first FPAC Node  install it is now time to configure your FPAC node ${Reset}"
# Stopping and restarting ax25
#  echo -e "${Green}\t Attempting to stop and restart AX.25${Reset}"
#  /etc/ax25/ax25-down
#  /etc/ax25/ax25-up
#(End of Script)
