#!/bin/sh -

# run as root 

# This is a shell script to install all software needed on a computer 
# with minimal installation of suse tumbleweed. 
# It can also be used for update of these pieces of software 
# although `zypper dup` shall be used. 
# This script is used prior to `zypper dup` 
# in order to inform the user about most significant changes. 
# Prior to invoking this, configure the zypper repositories 
# running addRepos.sh first. 

# To clean up the installed packages use 
# zypper packages --unneeded
# if <pkg> is listed before removing use 
# zypper rm <package> --dry-run
# Also useful: 
# zypper se --provides/-requires <package>

# Note that this script is for installation and for update only. 
# For deinstallation of a package, e.g. `squeak-vm`, run 
# zypper rm squeak-vm
# which will work if no dependencies on squeak-vm. 
# To eliminate unneededdependencies, e.g. those which became superfluous removing squeak-vm, let 
# zypper rm --clean-deps
#
# basically this insftallation script is based on invocations of zypper 
# but there are cases where other programs are used for installation 
# - zypper and rpm are present at the basic installation 
# - wget, curl, snapd and flatpak: must be installed and activated at first 
#   Currently, we try to refrain from snapd 
zypper in -y wget flatpak curl # snapd 
# systemctl enable snapd
# systemctl enable snapd.apparmor
# systemctl enable snapd.apparmor.service

# TBD: Snap applications work only on a second run, when snap demon is working 
# Thus first run of this script yields an error here. 
# Then one has to restart the computer and run this script once again. 
# This is not according to standard. 
# Solution: run only if  /run/snapd.socket exists. 
# else display a warning: restart computer and run this script again. 
# Snap refreshes automatically, snap refresh forces refresh 
# This is a major drawback of snap: automatic update 

# snap in something 

# snap refresh

# unlike for zypper which complains if a repo is added, 
# flatpak does not if we use --if-not-exists
# Thus we dont need a separate script for adding 
flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
#flatpak remote-add --if-not-exists flathub-beta https://flathub.org/beta-repo/flathub-beta.flatpakrepo

# GNOME Nightly: the newest but most unstable developer builds 
#flatpak remote-add --if-not-exists gnome-nightly https://nightly.gnome.org/gnome-nightly.flatpakrepo

# KDE: More stable although more current KDE-Apps 
#flatpak remote-add --if-not-exists kde https://distribute.kde.org/kdeapps.flatpakrepo

#Fedora: Takes care of Open-Source-Licenses more than Flathub.
#flatpak remote-add --if-not-exists fedora oci+https://registry.fedoraproject.org

instAsFlatpak() {
  local APP_ID=$1
  local TARGET=$2
  flatpak install --system -y flathub "$APP_ID"
  cat <<EOF > "$TARGET"
#!/bin/bash
flatpak run $APP_ID "\$@"
EOF
  chmod a+x "$TARGET"
}

instAsFlatpak "org.gaphor.Gaphor"  "/usr/bin/gaphor"
instAsFlatpak "com.github.Murmele.Gittyup" "/usr/bin/Gittyup"


# not permanently active 
# This is a fallback if version by zypper does not work 
# Note that if installing this, ltex does not work properly anymore with our setting 
#nstAsFlatpak "com.visualstudio.code" "/usr/bin/CODE"
# instAsFlatpak "org.onionshare.OnionShare" "/usr/bin/onionshare"
instAsFlatpak "com.rtosta.zapzap" "/usr/bin/whatsapp"
instAsFlatpak "org.signal.Signal" "/usr/bin/signal"
# contains gemini, chatgpt and leChat, could bear also whatsapp. 
instAsFlatpak "re.sonny.Tangram" "/usr/bin/tangram"
#instAsFlatpak "io.github.mrvladus.Gemini" "/usr/bin/gemini"
#instAsFlatpak "io.github.koromelodev.mindmate" "/usr/bin/chatgpt"
#instAsFlatpak "chat.mistral.ai" "/usr/bin/mistral"

instAsFlatpak "org.geogebra.GeoGebra" "/usr/bin/geogebra"

flatpak update -y


# uninstall 
#flatpak uninstall org.geogebra.GeoGebra
# list 
#flatpak list
# Dont forget to eliminate the bash script containing flatpak run... 

# downgrade: 
# list list the sequence of commits 
# $ flatpak remote-info --log flathub com.rtosta.zapzap
# update to a specific commit 
# $ flatpak update --commit=a4ae50678260bbc3020677dacb501856709f0d8e096885f03eb1deea88831c80 com.rtosta.zapzap

# defer update 
# $ flatpak mask com.rtosta.zapzap

# my personal printer driver... well not very generic (TBD: change that)
#rpm -i hll2350dwpdrv-4.0.0-1.i386.rpm

#/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"


# explanation on how to use wget: 
# -N  without --no-if-modified-since 
#     downloads only if the file on the server is newer or if the server does not provide a timestamp.  
#     In fact, it is to ensure that the newest variant of that file is available locally. 
#     This option shall be used if the file name does not include a version 
#     or more general, if there may be a newer variant of that file with the same name 
#     (e.g. because of a bugfix not reflected in the name of the file). 
# -N --no-if-modified-since
#     downloads in any case but if the file is present already, into a temporary file. 
#     If the temporary coincides with the original one, 
#     then the temporary one is ignored as if never downloaded. 
#     In particular the timestamp of the original file is kept. 
#     Only if the new file deviates, the original one is overwritten by the temporal one. 
#     This is if the server does not support modification time. 
#     Without --no-if-modified-since, wget would download for safety 
#     but then would give the new file a new timestamp in any case. 
#     Thus we would always reinstall. 
# -nc avoids downloading if it exists already. 
#     This shall be used if the file name is with version or more general, 
#     if there may be no newer variant on the server with the same name. 
# BUT: sometimes under the same version name e.g. 6.0 there are more versions like 6.0.1. 
# In this case, -N makes sense again. 
#
# always use wget .... "$URL" || echo "Downloading $FILE failed, skip installation/update. "
# in conlunction with 
# if [ $(stat -c %Y "$FILE") -ne "$OLD_TS" ]; then
#   ...
# If the file was not downloaded then 


# here comes all, this script requires. 
# Currently it is the json parser jq only. 
zypper in -y jq

# to locate e.g. my second monitor 
zypper in -y plocate libxcvt

# to replace dropbox 
zypper in -y tor torbrowser-launcher python3-onionshare 


zypper in -y MozillaThunderbird MozillaThunderbird-translations-common
# If the main directory is not preserved `~/.thunderbird` must be reconstructed.
# Also ensure that there is a link to thunderbird on the desktop

# addrepo.sh adds special repo for that 
zypper in -y google-chrome-stable mathjax dhcp-client

zypper in -y mozilla-openh264 # gstreamer-plugin-openh264 

# for version control; essentially git, but also rarely mercurial which installs perl as side effect
# To make accessible in dolphin also install according plugins
# also install some further GUIs but in the long run maybe replaced by vs code
zypper in -y git git-doc bash-git-prompt git-filter-repo git-lfs `# git` \
  mercurial `# mercurial` \
  dolphin-plugins gh gitg git-web git-cola glab git-mr `# GUI backends for git/mercurial` \
  kdiff3 kdiff3-lang tkdiff diffmk diff-pdf `# diffing tools` # meld mgdiff tdiff tkdiff


#zypper in -y kdiff3 kdiff3-lang diffmk diff-pdf # meld mgdiff tdiff tkdiff


# at the moment mainly for octave:
# programming languages: 
# - gcc currently mainly for octave (with documentation with doxygen)
# - scala for eval , 
# - go, smalltalk  
zypper in -y gcc gcc-c++ gcc-fortran gcc-ada gcc-go `# Also available: gcc-d, gcc-objc, gcc-obj-c++` \
  valgrind `# c instrumentation tool` \
  doxygen doxygen2man doxywizard `# doxygen, mainly for C` \
  autoconf automake libtool make `#make includes gnumake and cross platform cmake` \
  go-doc go `# go` \
  rustup `# rust with package manager cargo` \
  scala `# scala; maybe not enough` \
  julia `# julia, maybe really important` \
  mono-core `# mono used for tikz editor only `

#rustup default stable # not as root 
#rustup update disabled for suse, anyway, update with zypper instead 

# rustup self uninstall 

zypper in -y python313-torch

# If code/codium has a problem, go back to older version. 
zypper in -y emacs `#emacs-auctex, maybe emacs no longer needed, maybe aspell for emacs only` \
  aspell aspell-de aspell-fr aspell-it aspell-pt_BR aspell-tl `#spellchecker for emacs` \
  code \
  codium

# If code or codium chease to work properly after an update 
# download from https://github.com/VSCodium/vscodium/releases an older release as rpm file 
# which is someting like codium-1.116.02821-el8.x86_64.rpm 
# and install with 
# zypper in --oldpackage ~/Downloads/vscodium-*.rpm

# For VS code download from sth like: https://update.code.visualstudio.com/1.110.0/linux-rpm-x64/stable
# which yields sth like code-1.110.0-1772588031.el8.x86_64.rpm

# please for vs code run instVScode.sh also 
# Site with information on policies and listing policies 
# https://code.visualstudio.com/docs/enterprise/policies 




POLCD_DIR="/etc/vscodium"
mkdir -p "$POLCD_DIR"
pushd "$POLCD_DIR"
  cat > policies.json <<EOF
{
  "ExtensionGalleryServiceUrl": "",
  "Extensions.AutoCheckUpdates": false,
  "Extensions.AutoUpdates": false,
  "Extensions.IgnoreRecommendations": true,
  "Workbench.StartupEditor": "none",
  "Http.ProxySupport": "off",
  "Telemetry.BundleTelemetryLevel": "off"
}
EOF
popd

POLCO_DIR="/etc/opt/vscode/"
mkdir -p "$POLCO_DIR"
pushd "$POLCO_DIR"
ln -sf "$POLCD_DIR/policies.json" "$POLCO_DIR/policies.json"

# uninstall of code/codium: not only zypper rm code codium (maybe -u)
# rm -rf ~/.config/Code
# rm -rf ~/.config/VSCodium
# rm -rf ~/.vscode
# rm -rf ~/.vscode-oss
# rm -rf ~/.cache/vscode-cpptools
# rm -rf ~/.cache/Code

#exit 0

# texlive base and more 
zypper al texlive* # add lock 
#zypper rl texlive* # release lock 
zypper al latex2rtf # already locked because of recommended depencency to texlive 

# `okular` and `okular-lang` are installed in basic version but needed are also
# - spectre for forms and ps 
# - `evince` for support of xfa forms. 
#   As soon as okular supports them, evince is no longer needed. 
# - sioyek for jump to references *and back*, see formula and explanation, ... 
# - impressive: impressive presentation. 
zypper in -y okular-spectre evince sioyek impressive 

# geogebra has a tikz export 
# which may be steamlined with ktikz
# but this version is way tooo old; use flatpak instad 
#zypper in -y geogebra

zypper in -y \
  exif exiftool qpdf pdftk `# show exif meta data, exiftool is better ` \
    `# converter; texinfo implies texihtml and texiroff` \
  pandoc libreoffice libreoffice-kdeintegration `# unoconv below is based on libreoffice ` \
  LaTeXML unoconv \
    `# unoconv provides odt2doc, but also odt2bib, odt2docbook, odt2htm, odt2lt, odt2pdf, odt2rtf, odt2sdw, odt2sxw , odt2xhtml, odt2xml ` \
  xfig gnuplot inkscape `# converter` \
  libwebp-tools `# converter from webp to png, not yet used` \
  docbook2x discount `# the latter providing command 'markdown'` \
  glow glow-bash-completion `# markdown renderer ` \
  python313-pygments `# pygments e.g. for pythontex` \
  python3-linkchecker \
  ktikz `# if exports tikz together with geogebra may be a replacement for TikzEdt and also mono` \
  bibtool

#zypper in -y texinfo `# uses texlive teilweise` 
#zypper in -y \
#  rubber `# make utils texlive-arara? latexmake not present` \
#  epstool `# eps files in latex also for octave formerly ebb` \\
# itextpdf itextpdf-javadoc `# tool to sign pdf`
# ktikz `# tikz only viewer not editor and thus no replacement for TikzEdt and also mono` \


# TBD: have a look at the end of ~/.bashrc

# color functions 
error() { echo -e "\e[91m✖  ERROR: $1\e[0m"; exit 1; }
info()  { echo -e "\e[32m✔  INFO:  $1\e[0m"; }

# TBD: The following sections have some weakness to overcome 
# - the segments are quite similar, but not the same, maybe worth a redesign using a function. 
# - there are two variants of wget: -nc existence of file and -N newer. 
#   What to use depends on what the data source provides. 
# - the file to be downloaded. mostly some tar.gz serves as a hint whether to download anew. 
#   This requires additional space on disk. 
#   These files are never cleaned up 
# - some applications cause others to adapt, like ltex and the according vscode extension 


# info "Updating latex2rtf patched..."
# # install latex2rtf 
# INST_DIR=/opt/latex2rtf

# #LATEST_VERSION=$(curl -s https://api.github.com/repos/latex2rtf/latex2rtf-sf-files/releases/latest | jq -r .tag_name)
# # patch: 
# LATEST_VERSION="2.3.18"

# #FILE="$LATEST_VERSION.tar.gz"
# FILE="${LATEST_VERSION}patchedER.tar.gz"
# #URL="https://github.com/latex2rtf/latex2rtf-sf-files/archive/refs/tags/$FILE"
# URL="https://www.simuline.eu/Latex/$FILE"

# DIR="latex2rtf-sf-files-$LATEST_VERSION"

# mkdir -p "$INST_DIR"
# pushd "$INST_DIR"

#   # OLD_TS=0 if $FILE does not exist or timestamp cannot be found for some reason 
#   OLD_TS=$(stat -c %Y "$FILE" 2>/dev/null || echo 0)
#   wget -N --no-if-modified-since "$URL" || error "Downloading $FILE failed."

#   # NEW_TS=0 if $FILE does not exist or timestamp cannot be found for some reason 
#   NEW_TS=$(stat -c %Y "$FILE" 2>/dev/null || echo 0)
#   [ "$NEW_TS" -ne 0 ] || error "Something wrong with $FILE, download failed? - Skip installation/update."

#   if [ "$NEW_TS" -gt  "$OLD_TS" ]; then
#     rm -rf "$DIR"
#     tar xzf "$FILE"
#     cd "$DIR"
#     make clean 2>/dev/null || true   # falls vorher nichts gebaut wurde, Fehler ignorieren
#     make
#     make PREFIX="$INST_DIR" install

#     ln -sf "$INST_DIR/bin/latex2rtf" /usr/local/bin/latex2rtf
#   fi
# popd
# info "...done with latex2rtf"


# SRC_DIR=$(pwd)/forItextpdf
# echo $SRC_DIR

# INST_DIR="/opt/itextpdf"
# mkdir -p $INST_DIR
# pushd $INST_DIR
# cp -r "$SRC_DIR/src" .
# cp    "$SRC_DIR/pom.xml" .
# mvn package
# #ITEXTDIR="/usr/share/java/itextpdf"
# #ITEXTJARS="$ITEXTDIR/itext-pdfa.jar:$ITEXTDIR/itext-xtra.jar:$ITEXTDIR/itextpdf.jar:$ITEXTDIR/xmlworker.jar"
# #javac -cp "$ITEXTJARS" PdfSigner.java
# popd

# BIN_DIR=/usr/local/bin
# cp "$SRC_DIR/pdf-sign.sh" "$BIN_DIR/pdf-sign"
# chmod +x "$BIN_DIR/pdf-sign"

# exit 0


# set -x  # debug on 

info "Updating verapdf..."
# install veraPDF
FILE="verapdf-installer.zip"
URL="http://downloads.verapdf.org/rel/$FILE"

# OLD_TS=0 if $FILE does not exist or timestamp cannot be found for some reason 
OLD_TS=$(stat -c %Y "$FILE" 2>/dev/null || echo 0)
wget -N $URL || error "Downloading $FILE failed."

# NEW_TS=0 if $FILE does not exist or timestamp cannot be found for some reason 
NEW_TS=$(stat -c %Y "$FILE" 2>/dev/null || echo 0)
[ "$NEW_TS" -ne 0 ] || error "\Something wrong with $FILE, download failed? - Skip installation/update."

if [ "$NEW_TS" -gt  "$OLD_TS" ]; then
  rm -rf verapdf-greenfield*/
  unzip verapdf-installer.zip
  cd $(ls -d verapdf-greenfield*/)
  # write config for script installation 
  INST_DIR=/opt/verapdf
  # CAUTION: This auto-install.xml file may change with newer versions. 
  # It is possible to create this in the course of a manual installation 
  cat > auto-install.xml <<EOF
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<AutomatedInstallation langpack="eng">
    <com.izforge.izpack.panels.htmlhello.HTMLHelloPanel id="welcome"/>
    <com.izforge.izpack.panels.target.TargetPanel id="install_dir">
        <installpath>$INST_DIR</installpath>
    </com.izforge.izpack.panels.target.TargetPanel>
    <com.izforge.izpack.panels.packs.PacksPanel id="sdk_pack_select">
        <pack index="0" name="veraPDF GUI" selected="true"/>
        <pack index="1" name="veraPDF Mac and *nix Scripts" selected="true"/>
        <pack index="2" name="veraPDF Validation model" selected="true"/>
        <pack index="3" name="veraPDF Documentation" selected="true"/>
        <pack index="4" name="veraPDF Sample Plugins" selected="true"/>
    </com.izforge.izpack.panels.packs.PacksPanel>
    <com.izforge.izpack.panels.install.InstallPanel id="install"/>
    <com.izforge.izpack.panels.finish.FinishPanel id="finish"/>
</AutomatedInstallation>
EOF

  # invoke installer script 
  jarFile=$(ls verapdf-izpack-installer-*)
  java -jar $jarFile auto-install.xml
  # if auto-install.xml is out of date, this will fail. 
  # then restart without auto-install.xml. 
  # This starts a GUI and you can choose the selects and at the end you are asked to write a new auto-install.xml 

  # setup links 
  BIN_DIR=/usr/local/bin
  ln -sf "$INST_DIR/verapdf"     "$BIN_DIR/verapdf"
  ln -sf "$INST_DIR/verapdf-gui" "$BIN_DIR/verapdf-gui"
fi
info "...done with verapdf"

# set +x  # debug off 


# in the long run, we want more than one version. 
# a specific version via e.g. npm install "mathjax@3.2.2" --prefix "/opt/mathjax/3.2.2" --no-save
# we want a bunch of versions to use and to inlude in html created by latex-maven-plugin. 
# But for now, we dont care about reproducibility very much. 
info "Updating mathjax..."
INST_DIR=/opt/mathjax
LATEST_REMOTE_VER=$(npm view mathjax version)

# check whether a local version is installed 
if [ -f "$INST_DIR/latest/version.txt" ]; then
  # Here, mathjax is installed, get the version 
  LOCAL_VER=$(cat "$INST_DIR/latest/version.txt")
else
  # Here, mathjax is not installed, get a dummy version. 
  LOCAL_VER="0.0.0"
fi

# check on whether a new version is available 
if [ "$LATEST_REMOTE_VER" != "$LOCAL_VER" ]; then
  # need to install the new version 
    
  # Ensure the 'latest' directory is clean
  rm -rf "$INST_DIR/latest"
  mkdir -p "$INST_DIR/latest"
    
  # Install the new version
  npm install "mathjax@$LATEST_REMOTE_VER" --prefix "$INST_DIR/latest" --no-save
    
  # 3. Archive (Hardlink for history)
   echo "$LATEST_REMOTE_VER" > "$VERSION_DIR/version.txt"
fi

info "...done with mathjax"



info "Updating ltex..."

createLtexWrapper() {
  local APP=$1
  local LTEX_ROOT="$INST_DIR/$APPLICATION-latest"
  # To ensure that cat really overwrites (also if a link)
  rm -f "$APP"
  cat << EOF > "$APP"
#!/bin/bash
LTEX_ROOT="$LTEX_ROOT"
JAVA_HOME="\$LTEX_ROOT/jdk-latest" "\$LTEX_ROOT/bin/$APP-plus" "\$@"
EOF

# Root is the owner, others can read and execute 
chmod u=rwx,go=rx "$APP"
}

# ltex-plus replaced ltex because the latter seems no longer supported 
APPLICATION="ltex-ls-plus"
VERSION=$(curl -s "https://api.github.com/repos/ltex-plus/$APPLICATION/releases/latest" \
          | jq -r '.tag_name')
PLATTFORM=linux-x64
# If you dont want offline, just make this the empty string 
FILE="ltex-ls-plus-$VERSION-$PLATTFORM.tar.gz"
URL="https://github.com/ltex-plus/ltex-ls-plus/releases/download/$VERSION/$FILE"
INST_DIR="/opt/ltex"


mkdir -p $INST_DIR
pushd $INST_DIR

# OLD_TS=0 if $FILE does not exist or timestamp cannot be found for some reason 
OLD_TS=$(stat -c %Y "$FILE" 2>/dev/null || echo 0)
wget -nc "$URL" || error "Downloading $FILE failed."

# NEW_TS=0 if $FILE does not exist or timestamp cannot be found for some reason 
NEW_TS=$(stat -c %Y "$FILE" 2>/dev/null || echo 0)
[ "$NEW_TS" -ne 0 ] || error "Something wrong with $FILE, download failed? - Skip installation/update."

if [ "$NEW_TS" -gt  "$OLD_TS" ]; then
  # only here do anything. 
  tar --no-overwrite-dir --no-same-owner --no-same-permissions -xvzf $FILE
  # This is used by the code/codium extension 
  ln -fsn "$APPLICATION-$VERSION" "$APPLICATION-latest"
  cd "$APPLICATION-latest"
  JDK_ACTUAL=$(ls -d jdk* | head -n 1)
  ln -fsn "$JDK_ACTUAL" "jdk-latest"
  cd /usr/local/bin
  # This is used by the command line 
  createLtexWrapper ltex-ls
  createLtexWrapper ltex-cli
fi
popd

# write setting for as policy 

#VERSION=$(/usr/bin/codium --version 2>/dev/null | head -n 1)
VERSION=$(jq -r '.version' /usr/share/codium/resources/app/product.json)
echo $VERSION
MAJOR_MINOR=$(echo "$VERSION" | cut -d. -f1-2)
echo $MAJOR_MINOR
# minimal version of codium supporting policies 
REQUIRED="1.81"

[[ $(echo -e "$MAJOR_MINOR\n$REQUIRED" | sort -V | head -n1) == "$REQUIRED" ]] || \
  error "Use policies in version $VERSION but required $REQUIRED."

POLICY_DIR="/etc/vscodium/policies/managed"
mkdir -p "$POLICY_DIR"

# write policy with cat: cannot be overwritten 
cat << EOF > "$POLICY_DIR/ltex_global.json"
{
  "ltex.ltex-ls.path": "/opt/ltex/ltex-ls-plus-latest",
  "ltex.java.path": "$INST_DIR/$APPLICATION-latest/jdk-latest"
}
EOF

[ $? -eq 0 ] || error "Cannot write policy."

info "...done with ltex"


# TBD: This must be a separate script to be invoked by the user 
# To overwrite the local settings in a way, 
# that the global 
# INST_DIR="/opt/ltex"
# APPLICATION="ltex-ls-plus"
# LTEX_ROOT="$INST_DIR/$APPLICATION-latest"

# jq --arg ltex "$INST_DIR/$APPLICATION-latest" \
#    --arg java "$INST_DIR/$APPLICATION-latest/jdk-latest" \
#    '.["ltex.ltex-ls.path"] = $ltex | .["ltex.java.path"] = $java' \
#    settings.json > settings.json.tmp && mv settings.json.tmp settings.json



# # 1. VARIABLE: Dein Ziel-Objekt (Marketplace)
# NEW_GALLERY='{
#     "serviceUrl": "https://open-vsx.org/vscode/gallery",
#     "itemUrl": "https://open-vsx.org/vscode/item"
# }'

# # 2. ISOLIERTER EINGRIFF:
# # Nutze jq, um NUR den Zweig zu ändern, den du wirklich willst.
# # Wir speichern das Ergebnis erst in einer temporären Datei (.tmp).
# if jq --argjson gall "$NEW_GALLERY" '.extensionsGallery = $gall' "$PRODUCT_FILE" > "$PRODUCT_FILE.tmp"; then
    
#     # 3. VERIFIZIERUNG:
#     # Nur wenn jq erfolgreich war (Exit Code 0), überschreiben wir das Original.
#     mv "$PRODUCT_FILE.tmp" "$PRODUCT_FILE"
#     info "Product.json erfolgreich gepatcht."
# else
#     # Falls jq einen Syntax-Fehler meldet (z.B. weil product.json korrupt war)
#     error "Patch fehlgeschlagen! Originaldatei wurde NICHT verändert."
#     rm -f "$PRODUCT_FILE.tmp"
# fi


info "Updating genymotion..."
# genymotion android emulator. The site only offers version 3.9.0. 
# It is structured in a way that newer versions are not recognized. 
FOLDER="/usr/share/"
pushd $FOLDER # take care of cleanup
  VERSION="3.9.0"
  FILE="genymotion-$VERSION-linux_x64.run"
  URL="https://dl.genymotion.com/releases/genymotion-$VERSION/$FILE"

  # OLD_TS=0 if $FILE does not exist or timestamp cannot be found for some reason 
  OLD_TS=$(stat -c %Y "$FILE" 2>/dev/null || echo 0)

  # download if newer 
  wget -N $URL || error "Downloading $FILE failed."

  # NEW_TS=0 if $FILE does not exist or timestamp cannot be found for some reason 
  NEW_TS=$(stat -c %Y "$FILE" 2>/dev/null || echo 0)
  [ "$NEW_TS" -ne 0 ] || error "Something wrong with $FILE, download failed? - Skip installation/update."

  if [ "$NEW_TS" -gt  "$OLD_TS" ]; then
    # only here do anything. 
    chmod a+x ./$FILE
    . /$FILE
  fi
popd
info "...done with genymotion"

# TBD: replace all pushd by pushd > /dev/null
# what if it fails? 
# If fail: 
# - does not change folder. 
#   Means: nothing shall be done. 
#   Thus in an if construct we must skip all actions. 
# - does not add this folder onto the stack 
#   so it would be wrong to perform a popd. 
# Next subject; what if pushd succeeds but then popd fails? 
# exit this script. 
# This is save because this script is not invoked with source. 
# The script runs in a separate shell which is just closed. 
# So the original shell from which this script has been invoked may be still intact. 



info "Updating jabref..."
#set -x  # debug on 

# jabref: since jabref is updated frequently and update consumes a lot of time, 
# we decided to accept being outdated by MAX_AGE_DAYS. 
# Check for new updates only if older than that. 
# Another issue: 
# It is not desired to have a hard coded version here, but I did not find a good solution as yet. 
VERSION="6.0-1"
FILE="jabref-$VERSION.x86_64.rpm"
URL="https://builds.jabref.org/main/$FILE"
MAX_AGE_DAYS=14

pushd /usr/local/bin/
# Find conditions when to set doDownload=true
# If the file is not present or modification date is not readable, 
# the result is 0 
MOD_TIME=$(stat -c %Y "$FILE" 2>/dev/null || echo 0)
# The age is very high if the file is not present or mod date not readable 
age_days=$(( ($(date +%s)-MOD_TIME)/3600/24 ))
doDownload=true
# This if construct is to set doDownload=false if possible 
if [ "$age_days" -le "$MAX_AGE_DAYS" ]; then
  doDownload=false
else
  # if curl fails, true yields "" as standard output, so is REMOTE_SHA
  REMOTE_SHA=$(curl -s "$URL.sha256" || true)
  echo "REMOTE_SHA: $REMOTE_SHA"

  if [ -n "$REMOTE_SHA" ]; then
    # Here, the remote sha is known and so we shall compare with the local one 
    # sha256sum yields 'hash blank filename' we must cut off, i.e. split and preserve the 1st field. 
    # if sha256sum fails, the pipe is applied anyway but empty input empty output 
    LOCAL_SHA=$(sha256sum "$FILE" | cut -d' ' -f1)
    echo "LOCAL_SHA: $LOCAL_SHA"
    if [ "$REMOTE_SHA" = "$LOCAL_SHA" ]; then
      # This is the only case we can avoid the download 
      doDownload=false
    fi
  fi
fi

if [ "$doDownload" = true ]; then
    curl -LO "$URL"
    rpm -Uvh "$FILE"
fi

popd
info "...done with jabref"

#set +x  # Debugmodus an



#zypper in -y jabref # this did not work: older version, problem with javafx
# jabrefVersion=5.9-1.x86_64
# wget -nc -O ./jabref-$jabrefVersion.rpm https://www.fosshub.com/JabRef.html?dwl=jabref-$jabrefVersion.rpm
# rpm -i ./jabref-$jabrefVersion.rpm
# pushd /usr/local/bin/
# ln -sf /opt/jabref/bin/JabRef JabRef
# popd


# maybe needed more packages and higher versions
zypper in -y \
  java-11-openjdk-src java-11-openjdk java-11-openjdk-devel `# java11 already included in base installation ` \
	java-17-openjdk-src java-17-openjdk java-17-openjdk-devel `# java17 needed for redhead plugin` \
	java-21-openjdk-src java-21-openjdk java-21-openjdk-devel ` # java21 for curiosity` \
  java-1_8_0-openjdk-src java-1_8_0-openjdk java-1_8_0-openjdk-devel `# java1.8 for latex plugin` \
  `#openjfx # also for jabref` \
  maven `# basic build tool` \
  jenkins dejavu-fonts fontconfig 

# no longer update-alternaties, 
# instead alts is used. 
# This is used for console. 
# Note that jre and jdk are treated separately. 
# TBD: as based on priority rather than version, 



# # set back priorities to avoid setting JAVA_HOME in console to 21. 
# # this is a bit of a hack 
# for java_path in $(update-alternatives --list java); do
#     if [[ $java_path == *"21"* ]]; then
#         # JDK 17 → höchste Priority
#         update-alternatives --install /usr/bin/java java $java_path 2500
#     fi
# done

# # also for javac
# for javac_path in $(update-alternatives --list javac); do
#     if [[ $javac_path == *"21"* ]]; then
#         update-alternatives --install /usr/bin/javac javac $javac_path 2500
#     fi
# done

# some utilities 
zypper in -y kruler cheese `# webcam` \
  ripgrep `# speedy grep` \
  indent `# indent` \
  system-user-uucp uucp cutecom moreutils zip bzip2-doc gparted \
  dhex ktorrent stress-ng \
  memtest86+ \
  sensors acpi smartmontools hardinfo qt6-sensors `# temperature monitoring` \
  lshw sysstat `# hardware info` \
  xsane spectacle gimp k3b `# scanning, screenshot, image processing and burning` \
  vlc `# films` \
  htop `# memory consumption` \
  stress-ng `# stress test` \
  opi `# opensuse package installer without knowing the repo: for convenience use for codecs only ` \
  `#whatsapp-purple # displaylink not found` \
  `# the proper app: not working whatsie.x86_64 could be whatsapp-for-linux` \
  `# skype whatsapp is with snap currently, maybe skypeforlinux or flatpak` \
  kdeconnect-kde `# of course also on mobile kdeconnect must be installed. ` \
  dropbox-cli `# a drop box comand line client ` \
  luvcview `# driver for most webcams` \
  entr `# ls .latexmkrc | entr -c pod2html --infile=.latexmkrc --outfile=index.html invokes pod... if .latexmkrc changes`

opi -n codecs
  # TBD: use in general context: more vendors 
  # like chrome, codecs, dotnet, freeoffice, skype, teams-for-linux teamviewer zoom

# there are much more packages on octave-forge worth being investigated
# octave-devel is to be able to add packages
#rpm -i ./octave-5.2.0-lp152.2.4.x86_64.rpm ./octave-devel-5.2.0-lp152.2.4.x86_64.rpm 
#octave octave-devel 
zypper in -y octave octave-devel
zypper al "octave-forge-*"
octave -q --no-gui --eval "pkg install -forge cgi signal image interval data-smoothing statistics"
octave -q --no-gui --eval "pkg update" > /dev/null
# detete all packages: 
#octave --eval "p = pkg('list'); for i=1:length(p), pkg('uninstall', p{i}.name); endfor"

#  octave-forge-signal qhull 
  #`# what follows is for compiling octave itself`
#octave-forge-interval octave-forge-data-smoothing octave-forge-statistics 

# for miktex 
zypper in -y \
  qt6-base-devel qt6-concurrent-devel qt6-linguist-devel qt6-qml-devel \
  qt6-uitools-devel cairo-devel qt6-qt5compat-devel \
  libboost_locale-devel libboost_headers-devel fribidi-devel \
  gd-devel graphite2-devel harfbuzz-devel hunspell-devel liblog4cxx-devel \
  mpfi-devel `# multiprec. interval arith` \
  libmspack-devel popt-devel uriparser-devel zziplib-devel
 
zypper in -y \
  readline-devel rsvg-convert flex bison \
  f2c \
  gperf gperftools gperftools-devel gperftools-devel-static \
    libbz2-devel libcurl-devel qhull-devel icoutils \
   libQt5Core-devel libQt5Gui-devel \
    libQt5PrintSupport-devel libQt5Xml-devel libQt5Network-devel \
  qrupdate-devel sundials-devel sundials-doc \
    blas-devel libsndfile-devel fontconfig-devel \
  mpfr-devel `# for installing certain packages`

exit

# python 

zypper in -y python313-pipx python313-paramiko
#pipx install diff-pdf-visually


# what is needed for docker  
# decativated docker-kubic docker-kubic-bash-completion \
zypper in -y python3-docker #yast2-docker

# this is a hack only
if rpm -q firewalld  >/dev/null ;
then
    zypper rm -y python3-firewall firewalld firewalld-lang libnftables1
fi

systemctl enable docker
#usermod -aG docker `whoami`
#zypper in -y MicroOS-release # sth like alpine with 

# another containerization solution 
zypper in -y podman podmansh #podman-docker



zypper in -y inotify-tools



zypper in -y distrobox distrobox-bash-completion
# This was a trial on tikzit 
# more general, distrobox is very useful to invite other linux distributions 
#  libxcb-xkb-dev libxcb-render-util0-dev libxcb-image0 libxcb-keysyms1 libxcb-icccm4 libxcb-shape0-dev libxkbcommon-x11-0



zypper in -y yum rpm-build `#to build rpm packages`

# addrepo.sh adds special repo for that 

#zypper dist-upgrade -y --from packman --allow-vendor-change
# TBD: following not found
# libavcodec58 libavdevice58 libavfilter7 libavformat58 libavutil56 
zypper in -y gstreamer-plugins-good gstreamer-plugins-libav libavresample4 #vlc-codecs packman ffmpeg 


zypper in -y virtualbox

zypper in -y gnome-keyring

# Web development 
zypper in -y apache2-devel apache2-manual apache2-mod_php8 apache2-mod_perl
zypper in -y nodejs24 nodejs24-devel nodejs24-docs
zypper in -y nodejs-default nodejs-devel-default
zypper in -y nodejs-electron nodejs-electron-devel nodejs-electron-doc
zypper in -y tomcat10
# to use tomcat add 
#export CATALINA_HOME=/usr/share/tomcat/
#export CATALINA_BASE=/usr/share/tomcat/
# to your ~/.profile 


#zypper rm -y ksshaskpass

# deinstall python 2.7 and dependencies
# this is a hack only

#if rpm -q python  >/dev/null ;
#then
#  zypper rm -y gimp-plugins-python python-gobject2 python-gtk  python2-pycairo 
#  zypper rm -y python `# python-xml python-base` 
#  zypper rm -y libpython2_7-1_0
#fi

# Perl modules,.. mostly latex plugin, may be incomplete 
zypper in -y perl-PAR-Packer perl-PDF-API2 libexpat-devel
cpanm -n App::pod2pdf Pod::LaTeX

# OCR software
zypper in -y tesseract-ocr \
  tesseract-ocr-traineddata-deu tesseract-ocr-traineddata-eng tesseract-ocr-traineddata-fra \
   tesseract-ocr-traineddata-ita tesseract-ocr-traineddata-por


# for my android mobile 
zypper in -y mtp-tools libmtp9 simple-mtpfs


# What follows is installations through snap 

#zypper in -y teams
#if rpm -q teams  >/dev/null ;
#then
#      zypper rm -y teams
#fi
#
# already in zypper 



# TBD: eliminate hard coded path 
# install conda distribution
# mkdir -p ~ernst/SysAdmin/Addon/MiniConda
# wget -nc https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/Sysadmin/MiniConda/miniconda.sh
# bash ~ernst/SysAdmin/Addon/MiniConda/miniconda.sh -b -u -p ~ernst/SysAdmin/Addon/MiniConda
# rm -rf ~ernst/SysAdmin/Addon/MiniConda/miniconda.sh

# ~/SysAdmin/Addon/MiniConda/bin/conda init bash

# consult docs to uninstall conda 

#mkdir -p ~ernst/SysAdmin/Addon/PlantUML
#cp ./plantuml-1.2024.3_GPL.jar ~ernst/SysAdmin/Addon/PlantUML


pwd
