# Stolen from: https://gist.github.com/jjwatt/c83c02e6903c8ffaf546fe5eb27e7d25?permalink_comment_id=3305141#gistcomment-3305141
{ pkgs, ... }:
pkgs.stdenv.mkDerivation rec {
  name = "tic-80";
  src = pkgs.fetchgit {
    fetchSubmodules = true; # not supported by builtins.fetchGit :(
    url = "https://github.com/nesbox/TIC-80";
    rev = "0feb848378fc40d16aaa609ed7a2148d7a064ac4"; # v0.8 didn't look at what changed in the newer versions
    sha256 = "12fl9wfc1577rmzcll50r3hq582010bpwd3yi15ji2vadc2q1w9l";
  };
  buildInputs = with pkgs; [
    gcc
    pkg-config
    autoconf
    automake
    libtool
    pcre
    gnumake
    SDL2
    SDL2_gfx
    SDL_image
    SDL2_ttf
    SDL2_mixer
    harfbuzz
    curl
    gtk3
    gtk3-x11
    cmake
    cmakeCurses
    # elementary-cmake-modules
    extra-cmake-modules
    libglvnd
    mesa_glu
    mesa_glu
    freeglut
  ] ++ lib.optional stdenv.isLinux alsa-lib;

  configurePhase = ''
    echo [DIRECTORY] $(pwd)
    sed  -i 's/BUILD_PRO "Build PRO version" FALSE/BUILD_PRO "Build PRO version" TRUE/' CMakeLists.txt
    cd build/
    cmake ..
  '';

  buildPhase = ''
    make -j4
  '';

  installPhase = ''
    mkdir -p $out/bin
    chmod a+x bin/tic80
    cp -v bin/tic80 $out/bin

    # Create Desktop Item
    mkdir -p "$out/share/applications"
    ln -s "${desktopItem}"/share/applications/* "$out/share/applications/"

    mkdir -p "$out/share/icons/hicolor/128x128/apps"  # the long folder path is crucial, just using $out/share/icons does not work
    ln -s "$out/build/linux/tic80.png" "$out/share/icons/hicolor/128x128/apps/tic-80.png"
  '';

  desktopItem = pkgs.makeDesktopItem {
    name = "TIC-80";
    exec = "tic80 %U";
    comment = "Tiny Computer";
    categories = [ "Development" "Game" ];
    desktopName = "TIC-80";
    icon = "tic-80";
  };
}
