#!/bin/sh
# Shared packaged launcher: mutable files belong to the user, assets to the package.
set -e
case "$(uname -s)" in
    Darwin)
        PREFIX=$(CDPATH= cd -- "$(dirname -- "$0")/../Resources" && pwd -P)
        HOME_DIR="${TUCAN_HOME:-$HOME/Library/Application Support/Tucan Studio}"
        ;;
    *)
        PREFIX=/usr/lib/tucan-studio
        HOME_DIR="${TUCAN_HOME:-${XDG_DATA_HOME:-$HOME/.local/share}/tucan-studio}"
        ;;
esac
mkdir -p "$HOME_DIR"
HOME_DIR=$(CDPATH= cd -- "$HOME_DIR" && pwd -P)
if [ "$HOME_DIR" = "$PREFIX" ]; then
    echo 'TUCAN_HOME must be separate from the installed application.' >&2
    exit 1
fi

# Subshell scope keeps recursive source/destination variables independent.
# Include hidden files, preserve existing files (including symlinks), and merge
# new subdirectories. This also imports config/extensions from older Mac bundles
# when they are still present in the launched bundle.
copy_missing() (
    src=$1
    dst=$2
    [ -d "$src" ] || exit 0
    mkdir -p "$dst"
    for entry in "$src"/* "$src"/.[!.]* "$src"/..?*; do
        [ -e "$entry" ] || [ -L "$entry" ] || continue
        name=${entry##*/}
        target=$dst/$name
        if [ -d "$entry" ] && [ ! -L "$entry" ]; then
            if [ ! -e "$target" ] && [ ! -L "$target" ]; then
                mkdir -p "$target"
            fi
            if [ -d "$target" ] && [ ! -L "$target" ]; then
                copy_missing "$entry" "$target"
            fi
        elif [ ! -e "$target" ] && [ ! -L "$target" ]; then
            cp -pP "$entry" "$target"
        fi
    done
)
for name in config extensions; do
    copy_missing "$PREFIX/$name" "$HOME_DIR/$name"
done

# Refresh package-owned links when an app bundle moves or is upgraded. Keep
# real user files/directories. No mutable data is written into the app bundle.
for entry in "$PREFIX"/*; do
    [ -e "$entry" ] || continue
    name=${entry##*/}
    case "$name" in config|extensions) continue ;; esac
    target=$HOME_DIR/$name
    if [ -L "$target" ]; then
        rm "$target"
        ln -s "$entry" "$target"
    elif [ ! -e "$target" ]; then
        ln -s "$entry" "$target"
    fi
done
TUCAN_HOME=$HOME_DIR
export TUCAN_HOME
cd "$HOME_DIR"
exec "$PREFIX/app" "$@"
