#!/usr/bin/env bash
set -e

## Only deploy gcc matrix item
if [ "$CC" == "gcc" ]; then

  if [ "$TRAVIS_BRANCH" == "dev" ] || [ "$TRAVIS_BRANCH" == "master" ]; then
    # We need FPM
    gem install fpm

    ## Grab the version from package.yml
    VERSION=`grep -r version: package.yaml | cut -d "'" -f2`

    if [ "$TRAVIS_BRANCH" == "dev" ]; then
      FILE_VERSION=$VERSION~prerelease
      REPO_NAME=kitlang-prerelease
    fi

    if [ "$TRAVIS_BRANCH" == "master" ]; then
      FILE_VERSION=$VERSION
      REPO_NAME=kitlang-stable
    fi

    ## Create the Apt package
    fpm -s dir -t deb -n kitlang -v $FILE_VERSION-$TRAVIS_BUILD_NUMBER \
      --description "Kit is a programming language designed for creating concise, high performance cross-platform applications." \
      --license "LGPLv3.0" \
      --vendor "kitlang.org" \
      --maintainer "Ben Morris <ben@bendmorris.com>" \
      --url "https://kitlang.org" \
      -d "gcc | clang" \
      ~/.local/bin/kitc=/usr/bin/kitc std/=/usr/lib/kit toolchains/=/etc/kitlang/toolchains

    ## Create the RPM package
    fpm -s dir -t rpm -n kitlang -v $FILE_VERSION --iteration $TRAVIS_BUILD_NUMBER \
      --description "Kit is a programming language designed for creating concise, high performance cross-platform applications." \
      --license "LGPLv3.0" \
      --vendor "kitlang.org" \
      --maintainer "Ben Morris <ben@bendmorris.com>" \
      --url "https://kitlang.org" \
      -d "gcc" \
      ~/.local/bin/kitc=/usr/bin/kitc std/=/usr/lib/kit toolchains/=/etc/kitlang/toolchains

    ## Deploy the Apt package
    curl --show-error --fail -T kitlang_${FILE_VERSION}-${TRAVIS_BUILD_NUMBER}_amd64.deb -ubendmorris:$BINTRAY_API_KEY \
      -H "X-Bintray-Publish: 1" \
      -H "X-Bintray-Debian-Distribution: trusty,xenial,bionic" \
      -H "X-Bintray-Debian-Component: universe" \
      -H "X-Bintray-Debian-Architecture: amd64" \
      https://api.bintray.com/content/kitlang/$REPO_NAME-ubuntu/kitlang/$VERSION/kitlang_${FILE_VERSION}-${TRAVIS_BUILD_NUMBER}_amd64.deb

    ## Deploy the RPM package
    curl --show-error --fail -vvv -T kitlang-${FILE_VERSION}-$TRAVIS_BUILD_NUMBER.x86_64.rpm \
      -H "X-Bintray-Publish: 1" \
      -ubendmorris:$BINTRAY_API_KEY https://api.bintray.com/content/kitlang/$REPO_NAME-redhat/kitlang/$VERSION/kitlang-${FILE_VERSION}-$TRAVIS_BUILD_NUMBER.x86_64.rpm
  fi
fi
