#!/bin/bash
set -eu

if [ $(id -u) -ne 0 ]; then
    echo "E: $0 must be executed as root. Exiting!"
    exit 1
fi

###############
# Mount snaps #
###############

# Mount snaps packages to the location they are expected under /snap/
# The format of the name of the package must be:
# <NAME>_<VERSION>[_<ARCH>].snap

function mount_snaps() {
    for snap in $@; do
        snapname=$(basename "${snap}" .snap|cut -d_ -f1)
        snapvers=$(basename "${snap}" .snap|cut -d_ -f2)

        targetdir="/snap/${snapname}/${snapvers}"
        mkdir -p "${targetdir}"
        (
            cd "/snap/${snapname}/"
            rm -f current
            ln -s "${snapvers}" current
        )

        # Mount only once
        if ! grep -qs " ${targetdir} "; then
            mount -o loop "${snap}" "${targetdir}"
        fi
    done
}

snap_core=$(ls -1 /var/lib/snapd/snaps/core20_*.snap||true|sort -n -t_ -k2|tail -1)
snap_theme=$(ls -1 /var/lib/snapd/snaps/gtk-common-themes_*.snap||true|sort -n -t_ -k2|tail -1)
snap_wslsetup=$(ls -1 /var/lib/snapd/snaps/ubuntu-desktop-installer_*.snap||true|sort -n -t_ -k2|tail -1)

if [ -z "${snap_core}" ]; then
    echo "E: Could not find core20 snap"
    exit 1
elif [ -z "${snap_theme}" ]; then
    echo "E: Could not find gtk-common-themes snap"
    exit 1
elif [ -z "${snap_wslsetup}" ]; then
    echo "E: Could not find ubuntu-desktop-installer snap"
    exit 1
fi

mount_snaps "${snap_core}" "${snap_wslsetup}" "${snap_theme}"

#############################################
# Setup our mock snap environment variables #
#############################################

export SNAP=/snap/ubuntu-desktop-installer/current
export SNAP_REVISION="$(basename "${snap}" .snap|cut -d_ -f2)"
export SNAP_USER_DATA="${HOME}/snap/current/ubuntu-desktop-installer"
mkdir -p "${SNAP_USER_DATA}"
export SNAP_USER_COMMON="${HOME}/snap/common/ubuntu-desktop-installer"
mkdir -p "${SNAP_USER_COMMON}"
# We don't use the desktop extension runtime, everything is included in the snap itself.
export SNAP_DESKTOP_RUNTIME="${SNAP}"

# We don’t have dpkg-architecture to determine SNAP_ARCH
ARCH=$(arch)
if [ "$ARCH" = "x86_64-linux-gnu" ]; then
  SNAP_ARCH="amd64"
elif [ "$ARCH" = "arm-linux-gnu" ]; then
  SNAP_ARCH="armhf"
elif [ "$ARCH" = "aarch64-linux-gnu" ]; then
  SNAP_ARCH="arm64"
elif [ "$ARCH" = "powerpc64le-linux-gnu" ]; then
  SNAP_ARCH="ppc64el"
else
  SNAP_ARCH="$ARCH"
fi
export SNAP_ARCH

export XDG_RUNTIME_DIR="/run/user/${SUDO_UID}"
export SNAP_CORE_DIR="/snap/core20/current"

# Mount theme snap inside our snap
if ! grep -qs " $SNAP/data-dir "; then
    mount -o bind /snap/gtk-common-themes/current/share $SNAP/data-dir
fi

exec $SNAP/bin/ubuntu-wsl-setup $@
