#!/bin/bash

set -e

SCRIPT_PATH=$(dirname $0)

source $SCRIPT_PATH/_components_to_package.sh
source $SCRIPT_PATH/_common_functions.sh

DEB_VERSION="$1"

delete_files() {
  # $1 = package_name
  # $2 = package_name_short

  for suffix in alternatives \
      bash-completion \
      bug-script.in \
      config.in \
      copyright \
      dirs.in \
      install.in \
      links \
      lintian-overrides.in \
      postinst.in \
      postrm.in \
      templates.in \
      ; do


    case $suffix in
      alternatives|bash-completion|copyright|links)
        if [ -f "debian/$1.$suffix" ]; then
          rm "debian/$1.$suffix"
        fi
        ;;
      bug-script.in|templates.in)
        suffix_after=$(sed 's|\.in$||' <<< ${suffix})
        if [ -f "debian/$1.$suffix_after" ]; then
          rm "debian/$1.$suffix_after"
        fi
        ;;
      *)
        suffix_after=$(sed 's|\.in$||' <<< ${suffix})
        if [ -f "debian/$2.$suffix" ]; then
          if [ -f "debian/$1.$suffix_after" ]; then
            rm "debian/$1.$suffix_after"
          fi
        fi
        ;;
    esac
  done
}

for version in ${PLATFORMS_VERSIONS_TO_PACKAGE} \
    ${BUILD_TOOLS_VERSIONS_TO_PACKAGE} \
    ${PATCHER_VERSIONS_TO_PACKAGE} \
    ${CMDLINE_TOOLS_VERSIONS_TO_PACKAGE} \
    ${PLATFORM_TOOLS_VERSIONS_TO_PACKAGE} \
    ${NDK_VERSIONS_TO_PACKAGE} \
    ${SOURCES_VERSIONS_TO_PACKAGE} \
    ${EMULATOR_VERSIONS_TO_PACKAGE} \
    ${EXTRAS_GOOGLE_AUTO_VERSIONS_TO_PACKAGE} \
    ; do
  echo "    Cleaning autogenerated files for $version"
  delete_files "$(get_package_name "$version")" "$(get_package_name_short "$version")"
done

delete_files google-android-licenses google-android-licenses
