#!/bin/sh
# Install script for fluxClipboard suite (daemon + ctrl + dockapp).
# Installs binaries, man pages, and sample configs to ~/.local and ~/.config.

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PREFIX="${HOME}/.local"
BIN_DIR="${PREFIX}/bin"
MAN_DIR="${PREFIX}/share/man/man1"

BINS="fluxClip fluxClipCtrl fluxClipDock"
MANPAGES="fluxClip.1 fluxClipCtrl.1 fluxClipDock.1"

# Verify all binaries are present.
missing=""
for b in $BINS; do
    if [ ! -f "${SCRIPT_DIR}/${b}" ]; then
        missing="${missing} ${b}"
    fi
done
if [ -n "${missing}" ]; then
    echo "Error: missing binaries:${missing}" >&2
    echo "Build with: cargo build --release" >&2
    exit 1
fi

# Binaries.
mkdir -p "${BIN_DIR}"
for b in $BINS; do
    # Copy to a temporary name, then rename it over the old binary. Copying
    # straight onto a running binary fails with "Text file busy"; a rename
    # leaves the running copy alone until it exits.
    cp "${SCRIPT_DIR}/${b}" "${BIN_DIR}/.${b}.new.$$"
    chmod 755 "${BIN_DIR}/.${b}.new.$$"
    mv -f "${BIN_DIR}/.${b}.new.$$" "${BIN_DIR}/${b}"
    echo "Installed ${b} to ${BIN_DIR}/${b}"
done

# Man pages.
for m in $MANPAGES; do
    if [ -f "${SCRIPT_DIR}/${m}" ]; then
        mkdir -p "${MAN_DIR}"
        cp "${SCRIPT_DIR}/${m}" "${MAN_DIR}/${m}"
        chmod 644 "${MAN_DIR}/${m}"
        echo "Installed man page ${MAN_DIR}/${m}"
    fi
done

# Daemon config.
DAEMON_CFG_DIR="${HOME}/.config/fluxClipboard"
if [ -f "${SCRIPT_DIR}/config" ]; then
    mkdir -p "${DAEMON_CFG_DIR}"
    if [ -f "${DAEMON_CFG_DIR}/config" ]; then
        cp "${SCRIPT_DIR}/config" "${DAEMON_CFG_DIR}/config.sample"
        echo "Daemon config exists; installed sample to ${DAEMON_CFG_DIR}/config.sample"
    else
        cp "${SCRIPT_DIR}/config" "${DAEMON_CFG_DIR}/config"
        echo "Installed daemon config to ${DAEMON_CFG_DIR}/config"
    fi
fi

# Dockapp config.
DOCK_CFG_DIR="${HOME}/.config/fluxClipDock"
if [ -f "${SCRIPT_DIR}/config.dock" ]; then
    mkdir -p "${DOCK_CFG_DIR}"
    if [ -f "${DOCK_CFG_DIR}/config" ]; then
        cp "${SCRIPT_DIR}/config.dock" "${DOCK_CFG_DIR}/config.sample"
        echo "Dockapp config exists; installed sample to ${DOCK_CFG_DIR}/config.sample"
    else
        cp "${SCRIPT_DIR}/config.dock" "${DOCK_CFG_DIR}/config"
        echo "Installed dockapp config to ${DOCK_CFG_DIR}/config"
    fi
fi

echo "Done. Start the daemon with: fluxClip --background"
echo "Then add fluxClipDock to your Fluxbox slit."
