#!/usr/bin/env bash
##################################################################
##
##  Publish package to pub.dev
##
##  1. Run test case
##  2. Run code coverage
##  3. Analyze package scores
##  4. Local publish --dry-run
##  5. Deploy to pub.dev
##
##  Author: Chaobin Wu
##  Email : chaobinwu89@gmail.com
##
#################################################################

tag='[Deploy]'
error() {
  echo -e "\033[1m$tag\033[0m \033[31m$*\033[0m"
}
info() {
  echo -e "\033[1m$tag\033[0m \033[32m$*\033[0m"
}
warning() {
  echo -e "\033[1m$tag\033[0m \033[33m$*\033[0m"
}

die() {
  error "$*"
  exit 1
}

confirm() {
  read -p "Enter y to continue, otherwise terminate: " input
  if [[ $input != 'y' ]] ; then
    die "Workflow terminated"
  fi
}

# $1 = # of seconds
# $@ = What to print before "in n seconds"
countdown() {
  secs=$1
  shift
  msg=$@
  while [ $secs -gt 0 ]
  do
    printf "\r\033[K$msg in %.d seconds" $((secs--))
    sleep 1
  done
  echo
}

info "Start process workflow"
info "Step 1 Run test case with code coverage"

flutter pub get
flutter test --coverage && genhtml coverage/lcov.info --output=coverage
if [ ! $? = 0 ]; then
  die "Test failed"
fi

info "Step 2 Review code coverage report"
countdown 5 "Will open browser"
open coverage/index.html

confirm

info "Step 3 Generate score with pana"
pana --scores --source path ./
info "Review the score"
confirm

info "Step 4 Run publish --dry-run"
flutter pub publish --dry-run
confirm

info "Step 5 Publish to pub.dev"
flutter pub publish
if [ ! $? = 0 ]; then
  die "Test failed"
fi
info "Done!"