#!/bin/bash
set -eu

# build and release it

# Note: we need bionic meson version and sassc. As only those additions alongside git will be installed
# change directly sources.list
cmd="sed -i s/xenial/bionic/g /etc/apt/sources.list && apt update -qq && cd $(pwd) && snapcraft"

# Only release as a snap from main repo (ubuntu slug), enabling other forks to test build the snap.
# Notes that the tokens are only available when the source repo is under ubuntu/ project.
YARU_BRANCH="$TRAVIS_BRANCH"

if [ "$TRAVIS_BRANCH" == "bionic" ]; then
    if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
        # if it's a PR event, publish a special snap
        channel="edge/${TRAVIS_REPO_SLUG#*/}-pr$TRAVIS_PULL_REQUEST"
        YARU_BRANCH="$TRAVIS_PULL_REQUEST_BRANCH"
        echo "PR to bionic ubuntu repo: will release to $channel"
    else
        # this is an official edge snap
        channel="edge"
    fi
else
    echo "skipping: snaps are only for bionic builds"
    exit 0
fi

echo "Push to bionic ubuntu repo: will release to $channel"

cmd="$cmd && echo \"$SNAP_TOKEN\" | snapcraft login --with - && snapcraft push *.snap --release=$channel"

docker run -v $(pwd):$(pwd) -t snapcore/snapcraft:stable sh -c "$cmd"

# build now gtk-common-themes
# FIXME: we won't need this once snapd can accept and auto-install theme snaps.
mkdir -p ../gtk-common-themes/snap
cd ../gtk-common-themes

# get top part of original snapcraft.yaml and complete with new content
curl -o snap/snapcraft.yaml "https://gitlab.gnome.org/Community/Ubuntu/gtk-common-themes/raw/master/snap/snapcraft.yaml"
sed -i '/parts:/,$d' snap/snapcraft.yaml
sed -e "s,CHANNEL,$channel,g" -e "s,REPO,$TRAVIS_REPO_SLUG," -e "s,BRANCH,$YARU_BRANCH," "$TRAVIS_BUILD_DIR/build-helpers/gtk-common-themes-parts.yaml" >> snap/snapcraft.yaml

# build and push gtk-common-themes snap
cmd="sed -i s/xenial/bionic/g /etc/apt/sources.list && apt update -qq && cd $(pwd) && snapcraft"
cmd="$cmd && echo \"$SNAP_TOKEN\" | snapcraft login --with - && snapcraft push *.snap --release=$channel"
docker run -v $(pwd):$(pwd) -t snapcore/snapcraft:stable sh -c "$cmd"

# write on PR install instructions for the snap branch
[ "$TRAVIS_PULL_REQUEST" == "false" ] && exit 0
curl -H "Authorization: token ${GITHUB_TOKEN}" -X POST \
        -d "{\"body\": \"A new test snap version is available using: \`snap refresh communitheme --channel=$channel\`.\nFurther available updates will track that pull request then.\n\nSwitch back to stable or edge snap with \`snap refresh communitheme --stable\` or \`snap refresh communitheme --edge\` once you are done with it!\nYou may want to download as well \`gtk-common-themes\` snap from \`$channel\` channel to test your snaps with those changes.\n\nReplace \`refresh\` with \`install\` if you haven't installed the snap yet.\"}" \
        "https://api.github.com/repos/${TRAVIS_REPO_SLUG}/issues/${TRAVIS_PULL_REQUEST}/comments"
