#!/usr/bin/env bash
##makedesc: Install syncthing (latest) + ppa

set -eo pipefail

installed() { command -v "$1" >/dev/null 2>&1; }

download() {
    if installed wget; then
        wget -q --show-progress "$1" -O "$2"
    else
        curl -fsSL "$1" -o "$2"
    fi
}

install() {
    if [ "$(uname -s)" = "Darwin" ]; then
        if installed brew; then
            brew install syncthing
            brew services start syncthing
        else
            echo "ERROR: Install Homebrew first." >&2
            exit 1
        fi
        return
    fi

    echo
    echo "==============================================="
    echo "Installing syncthing"
    echo "==============================================="
    echo

    # https://apt.syncthing.net/

    # Add the release PGP keys:
    sudo curl -s -o /usr/share/keyrings/syncthing-archive-keyring.gpg https://syncthing.net/release-key.gpg

    # Add the channels to APT sources:
    echo "deb [signed-by=/usr/share/keyrings/syncthing-archive-keyring.gpg] https://apt.syncthing.net/ syncthing stable" | sudo tee /etc/apt/sources.list.d/syncthing.list
    echo "deb [signed-by=/usr/share/keyrings/syncthing-archive-keyring.gpg] https://apt.syncthing.net/ syncthing candidate" | sudo tee /etc/apt/sources.list.d/syncthing.list

    sudo apt update
    sudo apt install -y --autoremove syncthing

    mkdir -p "$HOME/.local/share/applications" "$HOME/.config/autostart"
    download "https://raw.githubusercontent.com/syncthing/syncthing/main/etc/linux-desktop/syncthing-start.desktop" "$HOME/.local/share/applications/syncthing-start.desktop"
    download "https://raw.githubusercontent.com/syncthing/syncthing/main/etc/linux-desktop/syncthing-ui.desktop" "$HOME/.local/share/applications/syncthing-ui.desktop"
    ln -sf "$HOME/.local/share/applications/syncthing-start.desktop" "$HOME/.config/autostart/syncthing-start.desktop"

    echo
    echo "Finish!"
    echo
}

case "$1" in
    *) install ;;
esac
