#!/usr/bin/env sh

# helper functions for strings
lowercase() {
  local string="${1}"

  if [ -z "${string}" ] && [ ! -t 0 ]; then
      string=$(cat <&0)
  fi

  echo ${string} | sed -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'
}

kebabcase() {
  local string="${1}"

  if [ -z "${string}" ] && [ ! -t 0 ]; then
      string=$(cat <&0)
  fi

  echo ${string} | tr '_' '-'
}

snakecase() {
  local string="${1}"

  if [ -z "${string}" ] && [ ! -t 0 ]; then
      string=$(cat <&0)
  fi

  echo ${string} | tr '-' '_'
}

random() {
  echo $(LC_CTYPE=C LANG=C tr -dc A-Za-z0-9 < /dev/urandom | fold -w ${1:-16} | head -n 1)
}

# help
usage() {
  cat << EOF
Usage:
  coast new <project-name>
  coast gen migration <name>
  coast gen code <table>
  coast db <migrate|rollback|create|drop>

Examples:
  coast new foo
  coast new another-foo

  coast gen migration create-table-todo     # Creates a new migration file
  coast gen sql:migration create-table-todo # Creates a new sql migration file

  coast gen code todo                       # Creates a new clj file with handler functions in src/todo.clj

  coast db migrate                          # runs all migrations found in db/migrations
  coast db rollback                         # rolls back the latest migration
  coast db create                           # creates a new database
  coast db drop                             # drops an existing database
EOF
  exit 0
}

if [ "$1" = "" ]
then
  usage;
fi

# new <project name>
if [ "$1" = "new" ]
then
  if [ "$2" != "" ]
  then
    name=$(kebabcase $(lowercase "$2"))
    sanitized=$(snakecase $(lowercase "$2"))
    secret=$(random)
    echo Downloading a fresh copy of coast...
    mkdir $2
    curl -fsSkL https://github.com/coast-framework/template/archive/master.tar.gz > master.tar.gz
    tar xzf master.tar.gz -C $2 --strip-components 1
    rm master.tar.gz
    cd $2
    mv gitignore .gitignore
    for f in $(find . -type f) ; do
      if [ $(uname) = "Darwin" ] # Mac
      then
        sed -i '' "s/{{name}}/$name/g" $f
        sed -i '' "s/{{sanitized}}/$sanitized/g" $f
        sed -i '' "s/{{secret}}/$secret/g" $f
      elif [ $(uname) = "Linux" ]
      then
        sed -i "s/{{name}}/$name/g" $f
        sed -i "s/{{sanitized}}/$sanitized/g" $f
        sed -i "s/{{secret}}/$secret/g" $f
      fi
    done

    echo "Created a new coast project in directory $2"
  fi
else
  clj -m coast.generators $@
fi

exit 0
