#!/bin/bash

# This is the folder where everything will be downloaded.
outputFolder="./greenspector"

# This is used if you DO NOT provide a "-v" flag.
defaultVersion=$(date '+%d-%m-%Y %H:%M')

# The pipeline will fail if the eco-score is less than $ecoScoreLimit. Set to 0 if you do no want to verify the eco-score.
ecoScoreLimit=50

##################################
## DO NOT TOUCH UNDER THIS LINE ##
##################################

cliFile="./gspt"
dashboardCampaignFile="./dashboard-campaign"
reportFile=".greenspector/testReport.json"

while getopts a:t:m:i:v:s:l:d:e flag; do
  case "${flag}" in
  c) coreserver=${OPTARG} ;;
  a) application=${OPTARG} ;;
  t) token=${OPTARG} ;;
  m) monitoredPackage=${OPTARG} ;;
  i) iterations=${OPTARG} ;;
  v) version=${OPTARG} ;;
  s) scriptFile=${OPTARG} ;;
  l) launchDashboardCampaign=${OPTARG} ;;
  d) definitionFile=${OPTARG} ;;
  e) environment=${OPTARG} ;;
  esac
done

if [ -z "$token" ]; then
  echo "Please provide a token with the -t flag."
  exit 1
fi

if [ -z "$application" ]; then
  echo "Please provide the application name with the -a flag."
  exit 1
fi

if [ -z "$monitoredPackage" ]; then
  echo "Please provide a package name to monitor with the -m flag."
  exit 1
fi

if [ -z "$launchDashboardCampaign" ]; then
  echo "Dashboard generation is skipped."
fi

if ! command -v curl &>/dev/null; then
  echo "curl could not be found"
  exit
fi

if ! command -v jq &>/dev/null; then
  echo "jq could not be found"
  exit
fi

coreserver=${coreserver:-"https://app.greenspector.com"}
iterations=${iterations:-1}
version=${version:-$defaultVersion}
scriptFile=${scriptFile:-"script.testgb"}
definitionFile=${definitionFile:-"./definition.yml"}
environment=${environment:-"mobile::Android::10::Samsung - Galaxy S9"}
launchDashboardCampaign=${launchDashboardCampaign:-"false"}


if [ ! -f "$scriptFile" ]; then
  echo "The script $scritFile does not exists"
  exit
fi

if [ $launchDashboardCampaign == "true" ]; then
  if [ ! -f "$definitionFile" ]; then
    echo "The definition file $definitionFile for the dashboard campaign does not exists"
    exit
  fi
fi

function fetch_modules() {
  curl -s -H "Private-Token: $token" $coreserver/api/modules >modules.json
}

function download_file() {
  URL="$coreserver$2"
  echo "Downloading $1 from $URL"
  curl -s -o "$3" "$URL"
}

function download_module() {
  download_file "$1" "$2" "$3"
  chmod +x "$3"
}

function download_dashboardCampagne() {
  dashboardCampaignCliURL=$(cat modules.json | jq -rc '.modules[] | select(.name == "Dashboard campaign CLI").archs[] | select(.name == "64-bit").links.Linux')
  assetsURL=$(cat modules.json | jq -rc '.modules[] | select(.name == "Definition Assets").link')
  configFileURL=$(cat modules.json | jq -rc '.modules[] | select(.name == "Config file Template").link')

  download_module "Dashboard campaign CLI" "$dashboardCampaignCliURL" "$dashboardCampaignFile"

  download_file "Dashboard campaign assets" "$assetsURL" assets.tar
  tar xf assets.tar
  rm -f assets.tar

  download_file "Dashboard campaign config template file" "$configFileURL" config.yml
}

function init_cli() {
  cliVersion=$(cat modules.json | jq -rc '.modules[] | select(.name == "Greenspector CLI").version')
  cliURL=$(cat modules.json | jq -rc '.modules[] | select(.name == "Greenspector CLI").archs[] | select(.name == "64-bit").links.Linux')

  if [ ! -f "$cliFile" ]; then
    echo "Greenspector CLI not found."
    download_module "Greenspector CLI" "$cliURL" "$cliFile"
  elif [ "greenspector version $cliVersion" != "$($cliFile -v)" ]; then
    echo "Greenspector CLI out-dated."
    download_module "Greenspector CLI" "$cliURL" "$cliFile"
  fi

  $cliFile i -a $coreserver/api -p "$token"
}

function launchMeasure() {
  $cliFile ping

  if [ ! $? -eq 0 ]; then
    echo "Could not ping Greenspector server use CLI."
    exit 1
  fi

  $cliFile ipc -a "$application" -v "$version"

  $cliFile testbench set-environment -e "$environment"

  $cliFile testbench custom-tests --testsSuite launch:./script.testgb \
    --monitoredPackage "$monitoredPackage" --iterations="$iterations" \
    -e PAUSEDURATION=30000 -e PAUSEAFTERLOAD=1000 \
    --networkMode=Wifi \
    --dd \
    --report

  if [ ! $? -eq 0 ]; then
    echo "Could not run the measure successfully."
    exit 2
  fi

  auditId=$(cat "$reportFile" | jq -c .audit.id)
  totalTest=$(cat "$reportFile" | jq -c .summary.tests.total)
  failedTest=$(cat "$reportFile" | jq -c .summary.tests.failed)

  if [ ! "$failedTest" -eq 0 ]; then
    echo "WARNING: $failedTest / $totalTest have failed."
    exit 3
  fi
}

function generateDashboard() {
  sed -i "s/TODO/$token/g" config.yml

  sed -i "s/id: .*/id: $auditId/g" definition.yml
  sed -i "s/idwifi: .*/idwifi: $auditId/g" definition.yml
  sed -i "0,/name/s/name: .*/name: $application/g" definition.yml
  sed -i "s/date: .*/date: $defaultVersion/g" definition.yml
  sed -i "s/- version: .*/- version: $version/g" definition.yml


  $dashboardCampaignFile -config config.yml -definition definition.yml

  if [ ! $? -eq 0 ]; then
    echo "Could not run the dashboard campaign."
    exit 4
  fi


  reportFileName=`printf "%s_%s_WIFI.html" "$application" "$version"`
  ecoScore=$(cat "./site/$application/$reportFileName" | grep "var ecoscoreValues" | cut -d'=' -f 2 | jq .[3])

  if [ -z $ecoScore ]; then
    echo "ERROR: Could not retrieve ecoscore"
    exit 4
  fi

  if (($ecoScore < $ecoScoreLimit)); then
    echo "ERROR: Eco score is less than $ecoScoreLimit: $ecoScore"
    exit 5
  fi

  echo "SUCCESS: Eco score is greater than $ecoScoreLimit: $ecoScore"
}

mkdir -p "$outputFolder"

cp "$scriptFile" ./"$outputFolder/script.testgb"
if [ $launchDashboardCampaign == "true" ]; then
  cp "$definitionFile" ./"$outputFolder/definition.yml"
fi
cd "$outputFolder"

fetch_modules

init_cli

# download dashboard if launch dashboard campaign is set
if [ $launchDashboardCampaign == "true" ]; then
  download_dashboardCampagne
fi

launchMeasure

## launch dashboard generation if definition file exists
if [ $launchDashboardCampaign == "true" ]; then
  generateDashboard
fi