final: prev:
let
  spotx = prev.fetchurl {
    url = "https://raw.githubusercontent.com/SpotX-Official/SpotX-Bash/c9b506c7749f853c827b6d4bd1d57818f953f68d/spotx.sh";
    hash = "sha256-irUHPR0Qdff2dpVtLNKGhgBBSd7Es1z7TkamxWi6JtI=";
  };

  # 맥 여부를 변수로 저장
  isDarwin = prev.stdenv.isDarwin;
in
{
  spotify = prev.spotify.overrideAttrs (old: {
    # 1. 의존성은 플랫폼에 상관없이 추가 (맥에서도 빌드 도구로 쓰일 수 있음)
    nativeBuildInputs = (old.nativeBuildInputs or [ ]) ++ (with prev; [
      util-linux
      perl
      unzip
      zip
      curl
    ]);

    # 2. unpackPhase: 맥이 아닐 때만 shebang 패치 적용
    unpackPhase = if (old ? unpackPhase && !isDarwin) then
      builtins.replaceStrings
        [ "runHook postUnpack" ]
        [
          ''
            patchShebangs --build ${spotx}
            runHook postUnpack
          ''
        ]
        old.unpackPhase
      else old.unpackPhase or null;

    # 3. installPhase: 맥이 아닐 때만 SpotX 스크립트 실행
    installPhase = if (old ? installPhase && !isDarwin) then
      builtins.replaceStrings
        [ "runHook postInstall" ]
        [
          ''
            bash ${spotx} -f -P "$out/share/spotify"
            runHook postInstall
          ''
        ]
        old.installPhase
      else old.installPhase or null;
  });
}
