#!/usr/bin/env bash
set -Eeuo pipefail
trap 'echo -e "\nErro na linha $LINENO. Veja o log em $LOG_FILE"; exit 1' ERR

SERVER="https://laucher.greenstorm.com.br"

APP_DIR="$HOME/.tropadoporco"
PRISM_DIR="$HOME/Library/Application Support/PrismLauncher"
INSTANCE_NAME="TropaDoPorco"
INSTANCE_PATH="$PRISM_DIR/instances/$INSTANCE_NAME"
JAVA_DIR="$APP_DIR/java"
LOG_DIR="$APP_DIR/logs"
LOG_FILE="$LOG_DIR/install.log"
USERNAME_FILE="$APP_DIR/username"

mkdir -p "$LOG_DIR"

log() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') | $1" | tee -a "$LOG_FILE"
}

ask() {
  echo -n "$1" > /dev/tty
  read -r answer </dev/tty
  printf '%s' "$answer"
}

pause() {
  echo
  read -r -p "Pressione ENTER para continuar..." </dev/tty
}

progress() {
  echo -e "\n[$1%] $2"
}

welcome() {
  clear
  echo "========================================"
  echo "   Tropa do Porco - Instalador Oficial"
  echo "========================================"
  pause
}

menu() {
  clear
  echo "1) Instalação inicial"
  echo "2) Recriar instância"
  echo "3) Atualizar ModPack"
  echo "0) Sair"
  OPTION=$(ask "Digite a opção: ")

  case "$OPTION" in
    0|1|2|3) ;;
    *)
      echo "Opção inválida."
      pause
      menu
      ;;
  esac
}

ask_username() {
  while true; do
    USERNAME=$(ask "Digite seu nome de jogador (3–16 letras/números/_): ")
    if [[ "$USERNAME" =~ ^[a-zA-Z0-9_]{3,16}$ ]]; then
      echo "$USERNAME" > "$USERNAME_FILE"
      break
    fi
    echo "Nome inválido."
  done
}

load_username() {
  if [ ! -f "$USERNAME_FILE" ]; then
    echo "Nome de usuário não encontrado. Rode a instalação inicial."
    exit 1
  fi
  USERNAME=$(cat "$USERNAME_FILE")
}

install_prism() {
  if [ -d "/Applications/Prism Launcher.app" ]; then
    log "Prism Launcher já instalado"
    return
  fi

  progress 5 "Instalando Prism Launcher"
  curl -L "$SERVER/prism/prism-mac.zip" -o /tmp/prism.zip
  unzip -o /tmp/prism.zip -d /Applications
}

install_java() {
  if [ -x "$JAVA_DIR/bin/java" ]; then
    log "Java já instalado"
    return
  fi

  progress 15 "Instalando Java 21"
  mkdir -p "$JAVA_DIR"
  curl -L "$SERVER/java/java-mac.tar.gz" | tar -xz -C "$JAVA_DIR" --strip-components=1
}

create_account() {
  UUID=$(uuidgen | tr -d '-')
  CLIENT_TOKEN=$(uuidgen | tr -d '-')
  IAT=$(date +%s)

  mkdir -p "$PRISM_DIR"

  cat > "$PRISM_DIR/accounts.json" <<EOF
{
  "accounts": [
    {
      "entitlement": { "canPlayMinecraft": true, "ownsMinecraft": true },
      "msa-client-id": "",
      "type": "MSA"
    },
    {
      "active": true,
      "entitlement": { "canPlayMinecraft": true, "ownsMinecraft": true },
      "profile": {
        "capes": [],
        "id": "$UUID",
        "name": "$USERNAME",
        "skin": { "id": "", "url": "", "variant": "" }
      },
      "type": "Offline",
      "ygg": {
        "extra": { "clientToken": "$CLIENT_TOKEN", "userName": "$USERNAME" },
        "iat": $IAT,
        "token": "0"
      }
    }
  ],
  "formatVersion": 3
}
EOF
}

create_instance() {
  rm -rf "$INSTANCE_PATH"
  mkdir -p "$INSTANCE_PATH"

  progress 40 "Criando instância"
  curl -L "$SERVER/base-instance.zip" -o /tmp/base.zip
  unzip -o /tmp/base.zip -d "$INSTANCE_PATH"

  sed -i '' "s/PlayerName=.*/PlayerName=$USERNAME/" "$INSTANCE_PATH/instance.cfg"

  cat >> "$INSTANCE_PATH/instance.cfg" <<EOF
OverrideJavaLocation=true
JavaPath=$JAVA_DIR/bin/java
EOF
}

download_mods() {
  progress 65 "Baixando mods"
  mkdir -p "$INSTANCE_PATH/.minecraft/mods"

  curl -s "$SERVER/mods/modlist.json" \
    | tr -d '[]" ' \
    | tr ',' '\n' \
    | while read -r mod; do
        [ -z "$mod" ] && continue
        echo "Baixando $mod"
        curl -fL "$SERVER/mods/$mod" \
          -o "$INSTANCE_PATH/.minecraft/mods/$mod"
      done
}

# =============== MAIN ===================
welcome
menu

case "$OPTION" in
  1)
    ask_username
    install_prism
    install_java
    create_account
    create_instance
    download_mods
    ;;
  2)
    load_username
    create_instance
    download_mods
    ;;
  3)
    load_username
    download_mods
    ;;
  0)
    exit 0
    ;;
esac

log "Instalador finalizado"
echo -e "\nInstalação concluída com sucesso!"