#!/bin/bash
# Wrapper script for Arduino IDE.
# On first run, creates per-user config and symlinks system-shipped
# indexes/packages into the user's data directory so the IDE does not
# need to download them from downloads.arduino.cc (which may be
# blocked by Cloudflare in some regions).

CONFDIR="$HOME/.arduinoIDE"
DATADIR="$HOME/.arduino15"
SKETCHDIR="$HOME/Arduino"
SYSFILES="/var/lib/arduino-ide"

mkdir -p "$CONFDIR"
mkdir -p "$SKETCHDIR"
mkdir -p "$DATADIR/staging"

# Create default CLI config if missing
if [ ! -f "$CONFDIR/arduino-cli.yaml" ]; then
    cat > "$CONFDIR/arduino-cli.yaml" <<EOF
board_manager:
  additional_urls: []
EOF
fi

# Symlink system indexes into user's data directory.
# Only create symlinks for items that do not already exist locally.
for item in package_index.json package_index.json.sig \
            library_index.json library_index.json.sig \
            inventory.yaml; do
    if [ ! -e "$DATADIR/$item" ] && [ -e "$SYSFILES/$item" ]; then
        ln -s "$SYSFILES/$item" "$DATADIR/$item"
    fi
done

# Symlink packages directory (contains pre-unpacked tools)
if [ -d "$SYSFILES/packages" ] && [ ! -e "$DATADIR/packages" ]; then
    ln -s "$SYSFILES/packages" "$DATADIR/packages"
fi

# Copy staging archives to user's directory (Arduino IDE will unpack them)
if [ -d "$SYSFILES/staging/packages" ]; then
    for archive in "$SYSFILES/staging/packages"/*.{tar.gz,tar.bz2,tar.xz}; do
        [ -f "$archive" ] || continue
        if [ ! -f "$DATADIR/staging/packages/$(basename "$archive")" ]; then
            mkdir -p "$DATADIR/staging/packages"
            cp -a "$archive" "$DATADIR/staging/packages/"
        fi
    done
fi

exec /opt/arduino-ide/arduino-ide "$@"
