#!/usr/bin/env nu
use std log

# Create temporary directory to store torrents
let temp_dir = (mktemp -d)
chmod 700 $temp_dir

# Download the torrents archive and save to temporary directory
let torrent_zip = ($temp_dir | path join "armbian-torrents.zip")
(
  http get -r "https://dl.armbian.com/torrent/all-torrents.zip"
  | save -r $torrent_zip
)

# Test torrent_zip for corruption
if (unzip -t $torrent_zip | complete | get exit_code) != 0 {
  log error "Error in zip";
  exit
}

# Extract torrent_zip
unzip -o $torrent_zip -d ($temp_dir | path join "torrent-tmp") | ignore

# Create list of current active Armbian torrent ids
let armbian_torrent_ids = (
  transmission-remote -n 'debian-transmission:debian-transmission' -l
  | from ssv
  | drop nth 0
  | drop
  | find "Armbian"
  | get ID
)

# Remove torrents from armbian_torrent_ids
$armbian_torrent_ids | each {
  |id|
  (
    transmission-remote -n 'debian-transmission:debian-transmission'
    -t $"($id)"
    --remove-and-delete
  )
} | ignore

# Add new/updated Armbian torrents
(
  ls ($temp_dir | path join "torrent-tmp")
  | get name
  | each {
    |torrent|
    transmission-remote -n 'debian-transmission:debian-transmission' -a $"($torrent)"
  } | ignore
)

# Clean up temporary directory
rm -rf $temp_dir