#!/usr/bin/bash

TYPE="$1"
case "$DRONE_BRANCH" in
  "production")
    OPTIONS="--release"
    ;;
  "")
    echo '$DRONE_BRANCH not set' >&2
    exit 1
    ;;
  *)
    OPTIONS="--debug"
    ;;
esac

curl https://codefirst.iut.uca.fr/git/Tactique-basket/Backend/raw/branch/dev/drone/prepare-deliver.sh > /tmp/prepare-deliver.sh
source /tmp/prepare-deliver.sh

SERV_DIR="$DIR/application/$TYPE"

case "$TYPE" in
  "android")
    OPTIONS="$OPTIONS -- --packageType=apk"
    OUT_DIR="platforms/android/app/build/outputs/apk"

    #install gradle
    wget -q https://services.gradle.org/distributions/gradle-7.5.1-bin.zip -P /tmp
    unzip -d /opt/gradle /tmp/gradle-*.zip > /dev/null
    export GRADLE_HOME=/opt/gradle/gradle-7.5.1/
    echo $GRADLE_HOME
    export PATH=$PATH:$GRADLE_HOME/bin
  ;;
  "browser")
    OUT_DIR="platforms/browser/www/"
    if [ "$DRONE_BRANCH" = "production" ]; then
      SERV_DIR="public_html/basket"
    else SERV_DIR="/server/apache/TBasket/"
    fi
  ;;
  "electron")
    OUT_DIR="platforms/electron/build"
  ;;
  *)
    echo "unrecognized platform $TYPE." >&2
  ;;
esac


#install cordova


cordova platform add "$TYPE" || exit 1
cordova build "$TYPE" $OPTIONS || exit 1
echo "delivering outputs on server"



echo "making delivery onto '$USER@$IP:$SERV_DIR'"
rsync -avz -I \
  --rsync-path="mkdir -p \"$SERV_DIR\" && rsync" \
  -e "ssh -o StrictHostKeyChecking=no" \
  --delete "$OUT_DIR" "$USER@$IP:/$SERV_DIR"