#!/usr/bin/env zsh

# Copyright notice
COPYRIGHT_TIME=2022
CURRENT_YEAR=`date +'%Y'`
if [ $CURRENT_YEAR -gt $COPYRIGHT_TIME ]; then
  COPYRIGHT_TIME="$COPYRIGHT_TIME-$CURRENT_YEAR"
fi
COPYRIGHT_USERS="`git config user.name` <`git config user.email`>"
if [ ! -z "$2" ]; then
  COPYRIGHT_USERS=`git blame $2 --line-porcelain | grep -e "^author " -e "^author-mail " | sed -e "s/^author //" -e "s/^author-mail //" | sed -e ':a;N;$!ba;s/\n</ </g' | sort -u | paste -sd "," -`
fi
COPYRIGHT_NOTICE="SPDX-FileCopyrightText: $COPYRIGHT_TIME $COPYRIGHT_USERS"

# License notice
LICENSE_NOTICE="SPDX-License-Identifier: AGPL-3.0-or-later"

if [ ! -z "$3" ]; then
  echo "$COPYRIGHT_NOTICE\n\n$LICENSE_NOTICE" > $2.license
  exit 0
fi


case "$1" in
  *.hs)
    COMMENT='--'
    ;;
  routes)
    COMMENT='--'
    ;;
  *.model)
    COMMENT='--'
    ;;
  *.hamlet)
    COMMENT='$#'
    ;;
  *.msg)
    COMMENT='#'
    ;;
  *.js)
    COMMENT='//'
    ;;
  *.julius)
    COMMENT='//'
    ;;
  *.sass)
    COMMENT='//'
    ;;
  *.cassius)
    COMMENT='//'
    ;;
  *.nix)
    COMMENT='#'
    ;;
  *.sh)
    COMMENT='#'
    ;;
  *.pl)
    COMMENT='#'
    ;;
  *.pm)
    COMMENT='#'
    ;;
  *.yaml)
    COMMENT='#'
    ;;
  *.yml)
    COMMENT='#'
    ;;
  *.md)
    COMMENT='[comment]: # ('
    COMMENT_END=' )'
    ;;
  *.txt)
    COMMENT='#'
    ;;
  *)
    echo 'Unsupported file extension'
    exit 1
esac

case "$1" in
  *.hamlet)
    echo "\$newline never\n" > $1
    echo "$COMMENT $COPYRIGHT_NOTICE$COMMENT_END\n$COMMENT$COMMENT_END" >> $1
    ;;
  *.sh)
    echo "#!/usr/bin/env bash\n" > $1
    echo "$COMMENT $COPYRIGHT_NOTICE$COMMENT_END\n$COMMENT$COMMENT_END" >> $1
    ;;
  *)
    echo "$COMMENT $COPYRIGHT_NOTICE$COMMENT_END\n$COMMENT$COMMENT_END" > $1
    ;;
esac

while IFS= read -r line
do
  echo "$COMMENT $line$COMMENT_END" >> $1
done < <(printf '%s\n' "$LICENSE_NOTICE")
