#!/bin/bash

#
# perltidy rules can be found in ../.perltidyrc
#
usage() {
    cat << EOF
Usage:
 tidy [-c|--check] [-f|--force] [-o|--only-changed] [-l|--list] [path/to/file]

Options:
 -h, -?, --help       display this help
 -c, --check          Only check for style check differences
 -q, --quiet          Only display errors
 -f, --force          Force check even if tidy version mismatches
 -o --only-changed    Only tidy files with uncommitted changes in git. This can
                      speed up execution a lot.
-l --list             List files tidy would touch
 path/to/file         When passing a file as argument, tidy will run perltidy
                      wether it is added to the git tree or not

perltidy rules can be found in .perltidyrc
EOF
    exit
}

set -eo pipefail
dir="$(dirname "$0")"

args=""
selection='--all'
[[ -e "$dir/perlfiles" ]] && selection=$("$dir"/perlfiles)
opts=$(getopt -o hcqfol --long help,check,quiet,force,only-changed,list -n "$0" -- "$@") || usage
eval set -- "$opts"
while true; do
  case "$1" in
    -h | --help ) usage ;;
    -c | --check ) args+=' --check-only'; shift ;;
    -q | --quiet ) args+=' --quiet'; shift ;;
    -f | --force ) force=true; shift ;;
    -o | --only-changed ) selection='--git'; shift ;;
    -l | --list ) args+='--list'; shift ;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

shift $((OPTIND - 1))
filename=${*:-"$selection"}

if ! command -v perltidy > /dev/null 2>&1; then
    echo "No perltidy found, install it first!"
    exit 1
fi

perltidy_version_expected=$(sed -n "s/^.*Perl::Tidy[^0-9]*\([0-9]*\)['];$/\1/p" "$dir"/../cpanfile)
# This might be used from another repo like os-autoinst-distri-opensuse
if [ -z "${perltidy_version_expected}" ]; then
    # No cpanfile in the linked repo, use the one from os-autoinst instead
    cpanfile_dir="$(dirname "$(readlink -f "$0")")"
    perltidy_version_expected=$(sed -n "s/^.*Perl::Tidy[^0-9]*\([0-9]*\)['];$/\1/p" "$cpanfile_dir"/../cpanfile)
fi
perltidy_version_found=$(perltidy -version | sed -n '1s/^.*perltidy, v\([0-9]*\)\s*$/\1/p')
if [ "$perltidy_version_found" != "$perltidy_version_expected" ]; then
    echo -n "Wrong version of perltidy. Found '$perltidy_version_found', expected '$perltidy_version_expected'. "
    if [[ "$force" = "true" ]]; then
        echo "Found '--force', continuing"
    else
        echo "Consider '--force' but results might not be consistent."
        exit 1
    fi
fi

# go to caller directory
cd "$dir/.."

# just to make sure we are at the right location
test -e tools/tidy || exit 1

# shellcheck disable=SC2086
tidyall $args $filename
