#!/usr/bin/env sh

say () {
  str=$1
  ruby -e "print \"\033[0;32m$1\033[0m\n\""
}

loudspeaker () {
  str=$1
  ruby -e "print \"\n\033[0;31m📢  📢  📢  $1\033[0m\n\n\""
}

say "Starting bootstrap\n"

git submodule update --init --recursive

ANDROID_STUDIO_PREFERENCES_PATH=`find ${HOME}/Library/Preferences -name 'AndroidStudio*' -depth 1 | sort -r | head -1`

if [ ! -d $ANDROID_STUDIO_PREFERENCES_PATH ]; then
  say "Android Studio expected in ${HOME}/Library/Preferences"
  exit 1
fi

# Signing config
test -e app/signing.gradle || cp app/signing.gradle.example app/signing.gradle

say "Running bundle install\n"
bundle install

say "Bootstrapping configs\n"
script/bootstrap_configs

# Update Kickstarter style
mkdir -p "${ANDROID_STUDIO_PREFERENCES_PATH}/codestyles"
ANDROID_STYLE_PATH="${ANDROID_STUDIO_PREFERENCES_PATH}/codestyles/Kickstarter.xml"
REPOSITORY_STYLE_PATH="script/style/Kickstarter.xml"

cmp -s "${ANDROID_STYLE_PATH}" "${REPOSITORY_STYLE_PATH}"
if [ $? -ne 0 ]; then
  if [ ! -f $ANDROID_STYLE_PATH ]; then
    loudspeaker "You need to switch to the Kickstarter code style in Android Studio. Update this setting in Preferences > Code Style. If Android Studio is currently open you may need to restart first to see the code style."
  else
    say "Updated Kickstarter code style, restart Android Studio to apply changes\n"
  fi
  cp $REPOSITORY_STYLE_PATH $ANDROID_STYLE_PATH
fi

# Remove author from new files
FILE_HEADER_PATH="${ANDROID_STUDIO_PREFERENCES_PATH}/fileTemplates/includes/File Header.java"
if [ -f "$FILE_HEADER_PATH" ]; then
  cat /dev/null > $FILE_HEADER_PATH
fi

# Install/update pidcat. Can also install pidcat via brew, but it's way out of date
curl -s "https://raw.githubusercontent.com/JakeWharton/pidcat/a6815e906a066b7b6e3ef93b989da52790174640/pidcat.py" > /tmp/pidcat
chmod +x /tmp/pidcat
cmp -s /tmp/pidcat /usr/local/bin/pidcat
if [ $? -ne 0 ]; then
  say "Updating pidcat\n"
  mv /tmp/pidcat /usr/local/bin/pidcat
fi

if [ ! -e "app/kickstarter.keystore" ]; then
  say "File \`app/kickstarter.keystore\` does not exist, this will prevent you from creating release builds."
  say "To fix this, download the keystore from \`s3://android-ksr-keystores/kickstarter.keystore\` to \`app/kickstarter.keystore\`.\n"
fi

if [ ! -e "app/signing.gradle" ]; then
  say "File \`app/signing.gradle\` does not exist, this will prevent you from creating release builds."
  say "To fix this, copy the example keystore from \`app/signing.gradle.example\` to \`app/signing.gradle\` then fill out the file with the correct credentials. These can be found in passpack under the entry Android - Keystore.\n"
fi

say "Bootstrap complete!"
