#!/bin/bash
# Wrapper script for Arduino IDE (ROSA package).
# On first run, seeds the user's config/data directories from the
# system-shipped offline bundle (/var/lib/arduino-ide) so the IDE works
# without network access (downloads.arduino.cc may be blocked), then
# launches the IDE on the system Electron.

CONFDIR="$HOME/.arduinoIDE"
DATADIR="$HOME/.arduino15"
SKETCHDIR="$HOME/Arduino"
SYSFILES="/var/lib/arduino-ide"
# Packaged settings templates (installed by the RPM into /usr/share/arduino-ide)
SHAREDIR="${ARDUINO_SHARE_DIR:-/usr/share/arduino-ide}"

mkdir -p "$CONFDIR"
mkdir -p "$CONFDIR/plugins" "$CONFDIR/extensions"
mkdir -p "$SKETCHDIR"
mkdir -p "$DATADIR/staging/packages"
mkdir -p "$DATADIR/packages"

# Create default CLI config from the packaged template (@HOME@ -> $HOME).
# directories.* are set explicitly so the IDE never runs the fallback
# `config dump` race (transient "Unexpected end of JSON input" at startup).
if [ ! -f "$CONFDIR/arduino-cli.yaml" ] && [ -f "$SHAREDIR/arduino-cli.yaml" ]; then
    sed "s|@HOME@|$HOME|g" "$SHAREDIR/arduino-cli.yaml" > "$CONFDIR/arduino-cli.yaml"
fi

# Machines configured before directories.builtin.libraries existed: the IDE's
# first-startup installer needs it to see the seeded Arduino_BuiltIn offline.
if [ -f "$CONFDIR/arduino-cli.yaml" ] \
   && ! grep -q "builtin:" "$CONFDIR/arduino-cli.yaml"; then
    # two separate passes: sed's `a` text is not rescanned within one run
    sed -i "/^  data: /a\\  builtin:" "$CONFDIR/arduino-cli.yaml"
    sed -i "/^  builtin:$/a\\    libraries: $HOME/.arduino15/libraries" "$CONFDIR/arduino-cli.yaml"
fi

# Disable IDE update check: with checkForUpdates=false and a valid channel
# ('stable') the IDE never contacts downloads.arduino.cc at startup.
if [ ! -f "$CONFDIR/settings.json" ] && [ -f "$SHAREDIR/settings.json" ]; then
    cp "$SHAREDIR/settings.json" "$CONFDIR/settings.json"
fi

# Migration for machines installed before the telemetry default flip: insert
# the key without touching the rest of the user's settings.json. Guarded:
# only pretty-printed files starting with a bare "{" line are patched.
if [ -f "$CONFDIR/settings.json" ] \
   && ! grep -q '"telemetry.enableTelemetry"' "$CONFDIR/settings.json" \
   && [ "$(head -n1 "$CONFDIR/settings.json")" = "{" ]; then
    sed -i '1a\    "telemetry.enableTelemetry": false,' "$CONFDIR/settings.json"
fi

# Purge stale .sig files seeded by pre-slim builds of this package: with a
# .sig next to the json the CLI checks signatures (and may try to re-fetch
# indexes); the package no longer ships them.
rm -f "$DATADIR/package_index.json.sig" "$DATADIR/library_index.json.sig"

# Copy indexes (not symlink!) so arduino-cli can write to them
for item in package_index.json library_index.json \
            package_index.tar.bz2 library_index.tar.bz2; do
    # Plain cp (NOT cp -a): arduino-cli treats a library index older than
    # ~24h as stale and tries to re-download it on any lib search/list — with
    # cp -a the files would keep the RPM build mtime and "expire" on machines.
    # Refreshing mtime at every start keeps the TTL always satisfied.
    [ -f "$SYSFILES/$item" ] && cp "$SYSFILES/$item" "$DATADIR/$item"
done
if [ ! -f "$DATADIR/inventory.yaml" ] && [ -f "$SYSFILES/inventory.yaml" ]; then
    cp -a "$SYSFILES/inventory.yaml" "$DATADIR/inventory.yaml"
fi

# Copy pre-unpacked packages (tools, platforms)
for pkg_dir in "$SYSFILES/packages"/*/; do
    pkg_name="$(basename "$pkg_dir")"
    if [ ! -d "$DATADIR/packages/$pkg_name" ]; then
        cp -a "$pkg_dir" "$DATADIR/packages/$pkg_name"
    fi
done

# Arduino_BuiltIn into the "ide" library location: the IDE's
# FirstStartupInstaller installs it with installLocation=BUILTIN on every
# startup until it succeeds; from the sketchbook alone the no-overwrite
# check would not see it (arduino-cli)
if [ -d "$SYSFILES/libraries/Arduino_BuiltIn" ] && [ ! -d "$DATADIR/libraries/Arduino_BuiltIn" ]; then
    mkdir -p "$DATADIR/libraries"
    cp -a "$SYSFILES/libraries/Arduino_BuiltIn" "$DATADIR/libraries/"
fi

# The AVR platform archive ships no boards.txt unpacked by default: unpack it
# into the user tree if the platform directory is still a stub
AVRDIR="$DATADIR/packages/arduino/hardware/avr/1.8.7"
if [ -f "$SYSFILES/staging/packages/avr-1.8.7.tar.bz2" ] && [ ! -f "$AVRDIR/boards.txt" ]; then
    mkdir -p "$AVRDIR"
    tar -xjf "$SYSFILES/staging/packages/avr-1.8.7.tar.bz2" -C "$AVRDIR" --strip-components=1
fi

# Migration for datadirs seeded by releases <= 7: their platform.txt passed
# "-C/etc/avrdude.conf" to avrdude (the avrdude 8.1 layout); avrdude 6.3
# (rosa2021.1) keeps its config in /etc/avrdude/ and fails to open the
# hardcoded path. Drop the "-C" flag so each avrdude version resolves its
# own compiled-in default config. Guarded by our cmd.path marker so the
# untouched upstream platform.txt of legacy prebuild datadirs is not touched.
if [ -f "$AVRDIR/platform.txt" ] \
   && grep -q '^tools.avrdude.cmd.path=/usr/bin/avrdude$' "$AVRDIR/platform.txt" \
   && grep -q -- '-C{config.path}' "$AVRDIR/platform.txt"; then
    sed -i 's| "-C{config.path}"||g' "$AVRDIR/platform.txt"
fi

# Copy bundled libraries into the USER sketchbook (~/Arduino/libraries).
# NB: not into ~/.arduino15/libraries ("ide" location): arduino-cli
# resolves "ide"-location libraries only via its daemon/library index,
# while the user sketchbook works both in the IDE and for standalone
# `arduino-cli compile` without extra flags.
if [ -d "$SYSFILES/libraries" ]; then
    mkdir -p "$SKETCHDIR/libraries"
    for lib_dir in "$SYSFILES/libraries"/*/; do
        lib_name="$(basename "$lib_dir")"
        # Arduino_BuiltIn lives ONLY in the builtin location (seeded above):
        # a second user-location copy would make two search-path hits
        if [ "$lib_name" = "Arduino_BuiltIn" ]; then continue; fi

        if [ ! -d "$SKETCHDIR/libraries/$lib_name" ]; then
            cp -a "$lib_dir" "$SKETCHDIR/libraries/$lib_name"
        fi
    done
fi

# Copy staging archives (IDE unpacks them when board is selected)
for archive in "$SYSFILES/staging/packages"/*; do
    [ -f "$archive" ] || continue
    if [ ! -f "$DATADIR/staging/packages/$(basename "$archive")" ]; then
        cp -a "$archive" "$DATADIR/staging/packages/"
    fi
done

exec /usr/bin/electron44 /usr/lib64/arduino-ide/resources/app "$@"
