#!/usr/bin/env bash

if [[ $# -eq 0 ]]; then
  exec google-chrome &
  exit 0
elif [[ $1 == "incognito" ]]; then
  exec google-chrome --incognito &
  exit 0
else
  for preffile in ~/.config/google-chrome/{Default*,Profile*}/Preferences; do
    [[ -e "$preffile" ]] || continue;
    profname=$(jq ".profile.name" "$preffile")
    echo "Found profile $profname in $preffile."
    if [[ "$profname" == "\"$1\"" ]]; then
      shift
      profdir=$(echo "$preffile" | sed -e 's|^.*google-chrome/\([^/]*\)/Preferences$|\1|')
      echo "Going to launch profile $profname with profile directory $profdir."
      exec google-chrome --profile-directory="$profdir" "$@" &
      exit 0
    fi
  done

  echo "Profile with name $1 not found!"
  exit 1
fi