diff --git a/common/all.nix b/common/all.nix new file mode 100644 index 0000000..7955580 --- /dev/null +++ b/common/all.nix @@ -0,0 +1,12 @@ +{}: + +# config that i use on all my hosts + +{ + # Set your time zone. + time.timeZone = "Europe/Vienna"; + + users.mutableUsers = false; + + nixpkgs.config.allowUnfree = true; +} diff --git a/common/me.nix b/common/me.nix new file mode 100644 index 0000000..8a3a0e6 --- /dev/null +++ b/common/me.nix @@ -0,0 +1,188 @@ + +{ pkgs, workDir, confDir, secretsDir, ... }: + +{ + imports = [ + ./programms/git.nix + ./programms/lf/default.nix + ./programms/alacritty.nix + ./programms/bash.nix + ./programms/emacs.nix + ./programms/rofi.nix + ./programms/zathura.nix + ./programms/ssh.nix + ./programms/neovim.nix + ]; + + home-manager.users.me = { config, pkgs, ... }: { + /* The home.stateVersion option does not have a default and must be set */ + home.stateVersion = "23.05"; + + gtk.cursorTheme = { + name = "Yaru"; + }; + + dconf.settings = { + "org/virt-manager/virt-manager/connections" = { + autoconnect = ["qemu:///system"]; + uris = ["qemu:///system"]; + }; + }; + + services.dunst.enable = true; + + home.sessionVariables = { + EDITOR = "nvim"; + }; + + home.sessionPath = [ "${workDir}/config/mybin" ]; + + home.file = { + ".config/rclone".source = config.lib.file.mkOutOfStoreSymlink "${secretsDir}/rclone-conf"; + }; + + }; + + fonts.fonts = with pkgs; [ + hack-font + ]; + + users.users.me = { + isNormalUser = true; + passwordFile = "${secretsDir}/main-user-pwd"; + extraGroups = [ "networkmanager" "wheel" "libvirtd" ]; # Enable ‘sudo’ for the user. + packages = with pkgs; [ + neovim + vim + obsidian + tree + xorg.xkbcomp + rofi + haskellPackages.xmonad-extras + haskellPackages.xmonad-contrib + alacritty + xorg.xev + ntfs3g + htop + subversion + pv + blueman + pavucontrol + spotify + flameshot + nodejs + neofetch + networkmanagerapplet + haskellPackages.xmobar + dolphin + mupdf + zathura + xclip + rclone + stalonetray + killall + nil + file + wstunnel + playerctl + alsa-utils + usbutils + pciutils + lshw + jmtpfs + pmutils + cntr + signal-desktop + element-desktop + discord + wireshark + zip + unzip + arp-scan + gparted + lolcat + android-tools + + # python.... + (python310.withPackages (p: with p; [ + pandas + click + click-aliases + ])) + + # base-devel + gcc + + # rust + cargo + rust-analyzer + + #localPacketTracer8 + + #ciscoPacketTracer8 + + # virtualisation + qemu + libvirt + virt-manager + freerdp + ]; + }; + +# xmonad + services.xserver.windowManager.xmonad = { + enable = true; + config = builtins.readFile ../misc/xmobar.hs; + enableContribAndExtras = true; + extraPackages = hpkgs: [ + hpkgs.xmobar + #hpkgs.xmonad-screenshot + ]; + ghcArgs = [ + "-hidir /tmp" # place interface files in /tmp, otherwise ghc tries to write them to the nix store + "-odir /tmp" # place object files in /tmp, otherwise ghc tries to write them to the nix store + #"-i${xmonad-contexts}" # tell ghc to search in the respective nix store path for the module + ]; + }; + + services.syncthing = { + enable = true; + user = "me"; + #dataDir = "/home/"; + configDir = "/home/me/.config/syncthing"; + extraFlags = ["-no-browser"]; + openDefaultPorts = true; + overrideDevices = true; # overrides any devices added or deleted through the WebUI + overrideFolders = true; # overrides any folders added or deleted through the WebUI + devices = { + "seb-phone" = { + id = builtins.readFile "${secretsDir}/syncthing-id-phone"; + #addresses = [ "tcp://192.168.200.24:22000" ]; + }; + "seb-tab" = { + id = builtins.readFile "${secretsDir}/syncthing-id-tab"; + #addresses = [ "tcp://192.168.200.26:22000" ]; + }; + }; + folders = { + "priv-share" = { # Name of folder in Syncthing, also the folder ID + path = "/home/me/work/priv-share"; # Which folder to add to Syncthing + #devices = [ "seb-phone" "seb-tab" ]; # Which devices to share the folder with + devices = [ "seb-phone" "seb-tab" ]; # Which devices to share the folder with + }; + }; + }; + fileSystems."${workDir}/priv-share/things" = { + device = "${workDir}/things"; + options = [ "bind" ]; + }; + fileSystems."${workDir}/things/htl" = { + device = "${workDir}/htl"; + options = [ "bind" ]; + }; + fileSystems."${workDir}/things/diplomarbeit" = { + device = "${workDir}/diplomarbeit"; + options = [ "bind" ]; + }; + +} diff --git a/common/nixos.nix b/common/nixos.nix new file mode 100644 index 0000000..51aff5a --- /dev/null +++ b/common/nixos.nix @@ -0,0 +1,17 @@ +{}: + +# config that i use on all my hosts, that run native nixos +# excluding for example my phone phone + +{ + + # Select internationalisation properties. + i18n.defaultLocale = "en_US.UTF-8"; + console = { + font = "Lat2-Terminus16"; + #keyMap = "at"; + useXkbConfig = true; # use xkbOptions in tty. + }; + +} + diff --git a/common/programms/alacritty.nix b/common/programms/alacritty.nix new file mode 100644 index 0000000..b11bb4f --- /dev/null +++ b/common/programms/alacritty.nix @@ -0,0 +1,109 @@ +{ ... }: +{ + home-manager.users.me.programms.alacritty = { + enable = true; + settings = { + font = { + normal = { + family = "Hack"; + style = "Regular"; + }; + + bold = { + family = "Hack"; + style = "Bold"; + }; + + italic = { + family = "Hack"; + style = "Italic"; + }; + + bold_italic = { + family = "Hack"; + style = "Bold Italic"; + }; + + size = 10; + }; + + # Dracula theme for alacritty + colors = { + primary = { + background = "#282a36"; + foreground = "#f8f8f2"; + bright_foreground = "#ffffff"; + }; + cursor = { + text = "CellBackground"; + cursor = "CellForeground"; + }; + vi_mode_cursor = { + text = "CellBackground"; + cursor = "CellForeground"; + }; + search = { + matches = { + foreground = "#44475a"; + background = "#50fa7b"; + }; + focused_match = { + foreground = "#44475a"; + background = "#ffb86c"; + }; + }; + footer_bar = { + background = "#282a36"; + foreground = "#f8f8f2"; + }; + hints = { + start = { + foreground = "#282a36"; + background = "#f1fa8c"; + }; + end = { + foreground = "#f1fa8c"; + background = "#282a36"; + }; + }; + line_indicator = { + foreground = "None"; + background = "None"; + }; + selection = { + text = "CellForeground"; + background = "#44475a"; + }; + normal = { + black = "#21222c"; + red = "#ff5555"; + green = "#50fa7b"; + yellow = "#f1fa8c"; + blue = "#bd93f9"; + magenta = "#ff79c6"; + cyan = "#8be9fd"; + white = "#f8f8f2"; + }; + bright = { + black = "#6272a4"; + red = "#ff6e6e"; + green = "#69ff94"; + yellow = "#ffffa5"; + blue = "#d6acff"; + magenta = "#ff92df"; + cyan = "#a4ffff"; + white = "#ffffff"; + }; + }; + + key_bindings = [ + { key = "V"; mods = "Control|Shift"; action = "Paste"; } + { key = "C"; mods = "Control|Shift"; action = "Copy"; } + { key = "J"; mods = "Control"; chars = ''\x1b\x5b\x42''; } + { key = "K"; mods = "Control"; chars = ''x1b\x5b\x41''; } + { key = "H"; mods = "Control"; chars = ''x1b\x5b\x44''; } + { key = "L"; mods = "Control"; chars = ''x1b\x5b\x43''; } + ]; + }; + }; +} diff --git a/common/programms/bash.nix b/common/programms/bash.nix new file mode 100644 index 0000000..f1e7034 --- /dev/null +++ b/common/programms/bash.nix @@ -0,0 +1,250 @@ +{ persistentDir, confDir, ... }: +{ + home-manager.users.me.programs.bash = { + + enable = true; + enableCompletion = true; + + historyFile = "${persistentDir}/bash-history"; + historyFileSize = 100000; + historyControl = "ignoredups"; + historyIgnore = [ + "ls" + "cd" + "exit" + ]; + + shellOptions = [ + # append to the history file, don't overwrite it + "histappend" + + # check the window size after each command and, if necessary, + # update the values of LINES and COLUMNS. + "checkwinsize" + + # If set, the pattern "**" used in a pathname expansion context will + # match all files and zero or more directories and subdirectories. + "globstar" + ]; + + sessionVariables = { + # is needed to that ssh works + TREM = "xterm"; + + # my prompt + PS1 = ''\[\033[01;34m\]\W\[\033[00m\]\[\033[01;32m\]\[\033[00m\] ❯❯❯ ''; + }; + + shellAliases = { + shutdown = "echo try harder.... xD"; + npw = "nmcli c up pw"; + nixre = "sd nixos-rebuild switch --flake ~/work/config/nix --impure"; + flex = "neofetch | lolcat"; + kwoche = "curl https://kalenderwoche.celll.net/?api=1; echo"; + psg = "ps -e | grep"; + vilias = "nvim -c 'set syntax=bash' ${confDir}/common/programs/bash.nix"; + stl = "sudo systemctl"; + vim = "nvim"; + sl = "ls"; + virsh = "virsh -c qemu:///system"; + nmgui = "nm-applet 2>&1 > /dev/null &; stalonetray 2>&1 > /dev/null; killall nm-applet"; + c = "cd .."; + ne= "alacritty &"; + cbs = "history | tail -n 2 | head -n 1 | awk '{\$1=\"\"; print \$0}' | cut -c 2- | cb"; + gs = "git status"; + gitlog = "git log --all --graph"; + ipa= '' + echo -e "IPv4:\n-----------------" + ip -o a show | cut -d " " -f 2,7 | grep -v : | column -t + echo -e "\nIPv6:\n-----------------" + ip -o a show | cut -d " " -f 2,7 | grep : | column -t + ''; + }; + + bashrcExtra = '' + # If not running interactively, don't do anything + case $- in + *i*) ;; + *) return;; + esac + + + # make less more friendly for non-text input files, see lesspipe(1) + [ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)" + + # making reverse search "going back" work with strg+s + stty -ixon + + + #################### functions #################### + + # A shortcut function that simplifies usage of xclip. + # - Accepts input from either stdin (pipe), or params. + # ------------------------------------------------ + cb() { + local _scs_col="\e[0;32m"; local _wrn_col='\e[1;31m'; local _trn_col='\e[0;33m' + # Check that xclip is installed. + if ! type xclip > /dev/null 2>&1; then + echo -e "$_wrn_col""You must have the 'xclip' program installed.\e[0m" + # Check user is not root (root doesn't have access to user xorg server) + elif [[ "$USER" == "root" ]]; then + echo -e "$_wrn_col""Must be regular user (not root) to copy a file to the clipboard.\e[0m" + else + # If no tty, data should be available on stdin + if ! [[ "$( tty )" == /dev/* ]]; then + input="$(< /dev/stdin)" + # Else, fetch input from params + else + input="$*" + fi + if [ -z "$input" ]; then # If no input, print usage message. + echo "Copies a string to the clipboard." + echo "Usage: cb " + echo " echo | cb" + else + # Copy input to clipboard + echo -n "$input" | xclip -selection c + # Truncate text for status + if [ ''${#input} -gt 80 ]; then input="$(echo $input | cut -c1-80)$_trn_col...\e[0m"; fi + # Print status. + echo -e "$_scs_col""Copied to clipboard:\e[0m $input" + fi + fi + } + + + # a little programm, that changes the ssh config to always be able to acces rpi + function rpi(){ + if [ "$1" == "l" ] + then + cp ~/work/config/ssh/rpi/local ~/work/config/ssh/current_pi_config + fi + + if [ "$1" == "local" ] + then + cp ~/work/config/ssh/rpi/local ~/work/config/ssh/current_pi_config + fi + + if [ "$1" == "r" ] + then + cp ~/work/config/ssh/rpi/remote ~/work/config/ssh/current_pi_config + fi + + if [ "$1" == "remote" ] + then + cp ~/work/config/ssh/rpi/remote ~/work/config/ssh/current_pi_config + fi + + if [ "$1" == "w" ] + then + cp ~/work/config/ssh/rpi/wstunnel ~/work/config/ssh/current_pi_config + fi + + } + + + # while true -> do cat..... + function follow (){ + while true; + do + cat $@; + done + } + + + # little looping func + function loop (){ + if [ "$1" == "-s" ] + then + for (( i=1; i<=$3; i++ )); do sleep $2; ''${@:4}; done + return + fi + case $1 in + ${"''"}|*[!0-9]*) + # infinit iterations + while true; do $@; done + return + ;; + *) ;; + esac + for (( i=1; i<=$1; i++ ));do ''${@:2}; done + } + + + function psk(){ + ps -e | grep $1 | awk '{print $1}' | xargs kill + } + + + sd() { + if [ "$1" == "" ] + then + sudo $(history | tail -n 2 | head -n 1 | awk '{$1=""; print $0}') + else + sudo $@ + fi + } + + + # rech + function rech(){ + python3 -c "print($@)" + } + + + # map + function map(){ + if [ "$1" == "" ] + then + bash ~/work/virtchord/reset + xmodmap \ + -e "clear control" \ + -e "clear mod1" \ + -e "keycode 64 = Control_L" \ + -e "keycode 37 = Alt_L" \ + -e "add control = Control_L" \ + -e "add mod1 = Alt_L" + + xset r rate 130 85 + + elif [ "$1" != "" ] + then + echo -en "set-map $1" > ~/work/config/virtchord/pipe1 + fi + } + + + # cf - copy file + function cf() { cat "$1" | cb; } + + + # shorter zathura + function zath(){ + zathura "$@" 2>/dev/null & + } + + + # shorter mupdf + function mu(){ + mupdf "$@" 1>/dev/null 2>/dev/null & + } + + + # ipaa + function ipaa(){ + ip -json addr show $1 | jq -r '.[] | .addr_info[] | select(.family == "inet") | .local' + } + + + #################### completions #################### + complete -cf sudo + complete -cf sd + complete -W "start stop restart status daemon-reload" stl + + # run + complete -W "mnt-wechner sync-school wstunnel hibernate p speed-test-nixos-iso bat bstat mnt-files-local mnt-lan-local mnt-files-remote mnt-lan-remote" ru + + + ''; + }; +} diff --git a/common/programms/emacs.nix b/common/programms/emacs.nix new file mode 100644 index 0000000..d7a8fee --- /dev/null +++ b/common/programms/emacs.nix @@ -0,0 +1,6 @@ +{ inputs, ... }: +{ + home-manager.users.me.programms.emcas = { + enable = true; + }; +} diff --git a/common/programms/git.nix b/common/programms/git.nix new file mode 100644 index 0000000..5c9b057 --- /dev/null +++ b/common/programms/git.nix @@ -0,0 +1,11 @@ +{ ... }: +{ + home-manager.users.me.programms.git = { + enable = true; + userName = "Sebastian Moser"; + userEmail = "sewi.moser@gmail.com"; + + extraConfig.core.editor = "nvim"; + extraConfig.core.excludesfile = "gitignore"; + }; +} diff --git a/common/programms/lf/default.nix b/common/programms/lf/default.nix new file mode 100644 index 0000000..497c259 --- /dev/null +++ b/common/programms/lf/default.nix @@ -0,0 +1,38 @@ +{ pkgs, ... }: +{ + home-manager.users.me.programs.lf = { + package = pkgs.lf.overrideAttrs (final: prev: { + patches = (prev.patches or [ ]) ++ [ + lib/patches/lf-filter.patch + ]; + checkPhase = ""; + }); + + enable = true; + commands = { + dragon-out = ''%${pkgs.xdragon}/bin/xdragon -a -x "$fx"''; + editor-open = ''$$EDITOR $f''; + mkdir = '' + ''${{ + printf "Directory Name: " + read DIR + mkdir $DIR + }} + ''; + }; + settings = { + preview = true; + drawbox = true; + icons = true; + }; + keybindings = { + "." = "set hidden!"; + "" = "open"; + do = "dragon-out"; + "gh" = "cd"; + "g/" = "/"; + ee = "editor-open"; + V = ''$${pkgs.bat}/bin/bat --paging=always --theme=gruvbox "$f"''; + }; + +} diff --git a/common/programms/lf/lf-filter.patch b/common/programms/lf/lf-filter.patch new file mode 100644 index 0000000..b7d0c21 --- /dev/null +++ b/common/programms/lf/lf-filter.patch @@ -0,0 +1,13 @@ +diff --git a/nav.go b/nav.go +index c32fc97..95cc2ce 100644 +--- a/nav.go ++++ b/nav.go +@@ -1774,7 +1774,7 @@ func searchMatch(name, pattern string) (matched bool, err error) { + if gOpts.globsearch { + return filepath.Match(pattern, name) + } +- return strings.Contains(name, pattern), nil ++ return strings.HasPrefix(name, pattern), nil + } + + func (nav *nav) searchNext() (bool, error) { diff --git a/common/programms/neovim.nix b/common/programms/neovim.nix new file mode 100644 index 0000000..c46e55b --- /dev/null +++ b/common/programms/neovim.nix @@ -0,0 +1,504 @@ +{ pkgs, ... }: +{ + home-manager.users.me.programms.neovim = { + enable = true; + withPython3 = true; + withNodeJs = true; + plugins = with pkgs.vimPlugins; [ + haskell-vim + plenary-nvim + # typst ... TODO + rust-vim + dracula-vim + ]; + + coc.enable = true; + coc.settings = { + "rust-analyzer.server.path" = "/etc/profiles/per-user/me/bin/rust-analyzer"; + "coc.preferences.extensionUpdateCheck" = "never"; + "cSpellExt.enableDictionaries" = [ "german" ]; + "cSpell.language" = "en,de"; + "rust-analyzer.enable" = true; + "rust-analyzer.diagnostics.enable" = true; + "rust-analyzer.checkOnSave.enable" = false; + "languageserver" = { + "vhdl" = { + "command" = "/home/sebastian/work/config/nvim/language-servers/vhdl/vhdl-tool"; + "args" = [ "lsp" ]; + "filetypes" = [ "vhdl" ]; + }; + "csharp-ls" = { + "command" = "csharp-ls"; + "filetypes" = [ "cs" ]; + "rootPatterns" = [ "*.csproj" ".vim/" ".git/" ".hg/" ]; + }; + "nix" = { + "command" = "nil"; + "filetypes" = [ "nix" ]; + "rootPatterns" = [ "flake.nix" ]; + }; + }; + "svelte.enable-ts-plugin" = true; + }; + + extraConfig = '' + + syntax enable + filetype plugin indent on + + " the nord colorscheme + "source ~/.config/nvim/plugins/nord-vim/colors/nord.vim + colorscheme dracula + + autocmd BufReadPost * call Setup() + + function Setup() + if index(["typst", "haskell", "tex", "c", "rust", "js", "vhdl"], &syntax) >= 0 + execute "call Setup_" . &syntax . "()" + endif + endfunction + + """"""""""""""""""""""""""""" mappings """"""""""""""""""""""""""""" + nmap gT + map gt + imap gT + imap gt + + map gt + map gT + imap gt + imap gT + + :tnoremap + :tmap + :tmap + + + cnoreabbrev ta Te + cnoreabbrev hh TSHighlightCapturesUnderCursor + + nnoremap ga :call CocActionAsync('doHover') + nnoremap gd :call CocActionAsync('jumpDefinition') + + nmap A; + + nmap zz + nmap zz + + nmap # * + + nmap ' /aöeiääääaöfj: + + nmap j gj + nmap k gk + nmap 0 g0 + nmap $ g$ + inoremap bcw + + cnoreabbrev s set filetype=javascriptreact + + nnoremap lua require('renamer').rename() + + "cmap t + "cmap + "cnoremap + "cnoremap + "cnoremap + "cnoremap + "cnoremap + "cnoremap + noremap i + set nohlsearch + set backupdir=~/.local/state/nvim/backup + + cnoreabbrev cdf :lcd %:p:h + cnoreabbrev tspell call CocAction('toggleExtension', 'coc-spell-checker') + + + + """"""""""""""""""""""""""""" neovide """"""""""""""""""""""""""""" + + " Being able to paste system clipboard in neovide + imap "+pi + nmap "+p + + vmap "+y + + + let g:neovide_cursor_vfx_mode = "wireframe" + set guifont=Hack:h10 + "set guifont=Monospace:h6 + + + + """"""""""""""""""""""""""""" coc """"""""""""""""""""""""""""" + + imap + imap + imap + imap + + "let g:coc_snippet_next = ${"''"} + "let g:coc_snippet_prev = ${"''"} + + "inoremap + "\ pumvisible() ? "\" : + "\ coc#jumpable() ? "\=coc#rpc#request('snippetNext', [])" : + "\ "\" + "inoremap + "\ pumvisible() ? "\" : + "\ coc#jumpable() ? "\=coc#rpc#request('snippetPrev', [])" : + "\ "\" + + " use enter for completing with coc + inoremap coc#pum#visible() ? coc#pum#confirm() : "\" + + + function! s:TernimalRun(cmd) + execute '5new' + call termopen(a:cmd, { + \ 'on_exit': 's:OnExit', + \ 'buffer_nr': bufnr('%'), + \}) + execute 'wincmd p' + endfunction + + + + """"""""""""""""""""""""""""" languages """"""""""""""""""""""""""""" + + " ###### typst ###### " + "Typst highlight customisation + function Setup_typst() + " set highlight of Headings to not be underlined + "autocmd TermClose * echo v:shell_error + "au TermClose * call feedkeys("ii") + :hi! link typstMarkupHeading markdownH1 + :hi markdownH1 cterm=bold, gui=bold + + " to keep indent the same when making a "-" list + set cindent + + cnoreabbrev c call SaveAndCompile_typst() + + function! OnExit(job_id, exit_code, event) dict + let lines = line("$") + if a:exit_code == "0" + "echo "good" + call feedkeys("ii") + else + "echo "bad" + endif + + + endfunction + + endfunction + + + function! SaveAndCompile_typst() + :silent w + "execute '5new' + let path = expand('%:p') + :belowright new 20split + ":belowright 20split call termopen("echo hello") + call termopen("typst --root ~/work/config/typst --font-path ~/config/typst/fonts compile " . path . " out.pdf", { + \ 'on_exit': 'OnExit', + \ 'buffer_nr': bufnr('%'), + \}) + "execute 'wincmd p' + ":execute '!typst compile ' . expand('%:p') + ":belowright 20split term://typst compile doku.typ + ":belowright 20split + "s:TernimalRun("!echo hello") + endfunction + + + + + " ###### js ###### " + set tabstop=3 shiftwidth=3 + function Setup_js() + + "autocmd Filetype js set tabstop=2 shiftwidth=2 expandtab + set tabstop=4 shiftwidth=4 + cnoreabbrev c echo JSSSSSSSSSSSSSSSSSS is interpreted..... + " autocmd Filetype setlocal ts=2 sw=2 expandtab + + endfunction + + + + " ###### c ###### " + function Setup_c() + cnoreabbrev c call SaveAndCompile_c() + endfunction + + + function! SaveAndCompile_c() + :w + execute '!gcc main.c -o main.out; if [ $? -ne 0 ]; then echo ======= ERROR =======; exit; fi ; echo "======= NO ERROR = PROGRAMM ======="; ./main.out' + endfunction + + + + " ###### latex ###### " + + let g:UltiSnipsExpandTrigger = '' + let g:UltiSnipsJumpForwardTrigger = '' + let g:UltiSnipsJumpBackwardTrigger = '' + + function Setup_tex() + set tabstop=2 shiftwidth=2 + "command SaveAndCompilelatex + cnoreabbrev c call SaveAndCompile_latex() + cnoreabbrev o call Open_latex() + + function Latex_toggle_comment() + let line=getline('.') + let chars = split(line, '\zs') + let index = 0 + while 1 + if len(chars) == 0 + return + break + endif + if chars[index] == " " + let index += 1 + else + break + endif + endwhile + if chars[index] == "%" + execute 's@^%@@g' + else + execute 's/^/%/g' + endif + endfunction + + vnoremap s :call Latex_toggle_comment() + endfunction + + function SaveAndCompile_latex() + :w + execute '!pdflatex --output-directory=' . expand('%:p:h') . " " . expand('%:p') + endfunction + + function Open_latex() + execute '!zathura ./main.pdf 1>/dev/null 2>/dev/null &' + endfunction + " end latex + + + " ###### vhdl ###### " + + function Setup_vhdl() + function Vhdl_toggle_comment() + let line=getline('.') + let chars = split(line, '\zs') + let index = 0 + while 1 + if len(chars) == 0 + return + break + endif + if chars[index] == " " + let index += 1 + else + break + endif + endwhile + if chars[index] == "-" + execute 's@^--@@g' + else + execute 's/^/--/g' + endif + endfunction + + vnoremap s :call Vhdl_toggle_comment() + + endfunction + + " ###### haskell ###### " + + function Setup_haskell() + set tabstop=4 shiftwidth=4 expandtab + + "command SaveAndCompile_haskell + cnoreabbrev c call SaveAndCompile_haskell() + "command Debugger_haskell + cnoreabbrev d call Debugger_haskell() + endfunction + + + function SaveAndCompile_haskell() + :w + execute '!ghc ' . @% + endfunction + + + function Debugger_haskell() + :w + execute '!ghci ' . @% + endfunction + + let g:haskell_classic_highlighting = 0 + let g:haskell_indent_if = 3 + let g:haskell_intdent_disable = 0 + let g:haskell_indent_case = 2 + let g:haskell_indent_let = 4 + let g:haskell_indent_where = 6 + let g:haskell_indent_before_where = 2 + let g:haskell_indent_after_bare_where = 2 + let g:haskell_indent_do = 3 + let g:haskell_indent_in = 1 + let g:haskell_indent_guard = 2 + let g:haskell_indent_case_alternative = 1 + let g:cabal_indent_section = 2 + + + + " ###### rust ###### " + + function Setup_rust() + + vnoremap s :call Rust_toggle_comment() + + cnoreabbrev c call Cargo_ceck() + cnoreabbrev r call Cargo_run() + cnoreabbrev b call Cargo_build() + + endfunction + + function Cargo_build() + :w + ":term cargo build + :belowright 20split term://cargo build + endfunction + + function Cargo_run() + :w + ":term cargo run + :belowright 20split term://cargo run + endfunction + + "tnoremap J :call Cargo_jump() + augroup MyTermMappings + autocmd! + autocmd TermOpen * nnoremap J :lua Cargo_jump() + augroup END + + function Cargo_ceck() + :w + :belowright 20split term://cargo check + endfunction + + function Rust_toggle_comment() + let line=getline('.') + let chars = split(line, '\zs') + let index = 0 + while 1 + if len(chars) == 0 + return + break + endif + if chars[index] == " " + let index += 1 + else + break + endif + endwhile + if chars[index] == "/" + execute 's@^//@@g' + else + execute 's/^/\/\//g' + endif + endfunction + ''; + + extraLuaConfig = '' + function Cargo_jump() + local line,c = unpack(vim.api.nvim_win_get_cursor(0)) + local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false) + + local line_iter = line + local line_to_jump = nil + local file_to_jump = nil + while true do + if (lines[line_iter]:sub(1,6) == "error[") then + local split_line = mysplit(lines[line_iter +1], ":") + line_to_jump = split_line[2] + file_to_jump = split_line[1]:sub(6, -1) + break + end + line_iter = line_iter - 1 + end + + local buffers = get_buffers() + local abs_file_to_jump = vim.fn.getcwd() .. "/" .. file_to_jump + + for i,buf in pairs(buffers) do + local name = vim.api.nvim_buf_get_name(buf) + if name == abs_file_to_jump then + local tab_num = get_tab(name) + --vim.cmd("tabn 2") + return + else + end + end + vim.cmd(":tabnew" .. abs_file_to_jump) + end + + function get_tab(name) + print("there") + local listing = vim.api.nvim_command_output("tabs") + for i,line in pairs(mysplit(listing, "\n")) do + if line:sub(1,8) == "Tab page" then + local tab = line:sub(-1) + print("tab:", tab) + else + local file = line:sub(5,-1) + end + end + end + + function mysplit (inputstr, sep) + if sep == nil then + sep = "%s" + end + local t={} + for str in string.gmatch(inputstr, "([^"..sep.."]+)") do + table.insert(t, str) + end + return t + end + + + function dump(o) + if type(o) == 'table' then + local s = '{ ' + for k,v in pairs(o) do + print(k) + if type(k) ~= 'number' then k = '"'..k..'"' end + s = s .. '['..k..'] = ' .. dump(v) .. ',' + end + return s .. '} ' + else + return tostring(o) + end + end + + function get_buffers() + local buffers = {} + + for buffer = 1, vim.fn.bufnr('$') do + local is_listed = vim.fn.buflisted(buffer) == 1 + table.insert(buffers, buffer) + end + + return buffers + end + + ''; + }; +} diff --git a/common/programms/rofi.nix b/common/programms/rofi.nix new file mode 100644 index 0000000..06029cc --- /dev/null +++ b/common/programms/rofi.nix @@ -0,0 +1,14 @@ +{ ... }: +{ + home-manager.users.me.programs.rofi = { + enable = true; + theme = "Ark-Dark by leofa"; + extraConfig = '' + modi: "run,filebrowser"; + color-normal: "#1c2023, #919ba0, #1c2023, #a4a4a4, #1c2023"; + color-urgent: "argb:00000000, #f43753, argb:00000000, argb:00000000, #e29a49"; + color-active: "argb:00000000, #49bbfb, argb:00000000, argb:00000000, #e29a49"; + color-window: "#1c2023, #919ba0, #1c2023"; + ''; + }; +} diff --git a/common/programms/ssh.nix b/common/programms/ssh.nix new file mode 100644 index 0000000..d735a8f --- /dev/null +++ b/common/programms/ssh.nix @@ -0,0 +1,148 @@ +{ secretsDir, ... }: +{ + home-manager.users.me.programms.ssh = { + enable = true; + includes = [ "./current_rpi_config" ]; + matchBlocks = { + hpm = { + hostame = "192.168.1.56"; + use = "root"; + }; + + servers = { + hostname = "192.168.1.3"; + user = "server"; + extraConfig = '' + AddKeysToAgent yes + ''; + identityFile = "${secretsDir}/private-key-main"; + }; + + server = { + hostname = "192.168.1.3"; + user = "admin"; + extraConfig = '' + AddKeysToAgent yes + ''; + identityFile = "${secretsDir}/private-key-main"; + }; + + ocia = { + hostname = "140.238.212.229"; + user = "root"; + identityFIle = "${secretsDir}/private-key-ocia"; + }; + + ocib = { + hostname = "140.238.211.43"; + user = "root"; + identityFIle = "${secretsDir}/private-key-ocib"; + }; + }; + }; + + home-manager.users.me.home.".ssh/rpi/local".text = '' + Host config + HostName 192.168.1.2 + User config + Port 49388 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + #RemoteCommand cd /svn/config; bash + + Host rpi + HostName 192.168.1.2 + User admin + Port 49388 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + + Host files + HostName 192.168.1.2 + User files + Port 49388 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + + Host rpis + HostName 192.168.1.2 + User server + Port 49388 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + ''; + + home-manager.users.me.home.".ssh/rpi/remote".text = '' + Host config + HostName sebastian.dns.army + User config + Port 49388 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + #RemoteCommand cd /svn/config; bash + + Host rpi + HostName sebastian.dns.army + User admin + Port 49388 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + + Host files + HostName sebastian.dns.army + User files + Port 49388 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + + Host rpis + HostName sebastian.dns.army + User server + Port 49388 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + ''; + + home-manager.users.me.home.".ssh/rpi/wstunnel".text = '' + Host config + HostName localhost + User config + Port 55555 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + #RemoteCommand cd /svn/config; bash + + Host rpi + HostName localhost + User admin + Port 55555 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + + Host files + HostName localhost + User files + Port 55555 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + + Host rpis + HostName localhost + User server + Port 55555 + AddKeysToAgent yes + #UseKeychain yes + IdentityFile ${secretsDir}/private-key-main + ''; +} diff --git a/common/programms/zathura.nix b/common/programms/zathura.nix new file mode 100644 index 0000000..26d291f --- /dev/null +++ b/common/programms/zathura.nix @@ -0,0 +1,41 @@ +{ ... }: +{ + home-manager.users.me.programms.zathura = { + enable = true; + options = { + selection-clipboard = "clipboard"; + roll-step = 40; + }; + mappings = { + "" = ''scroll down''; + "" = ''scroll up''; + "" = ''scroll left''; + "" = ''scroll right''; + + "j" = ''feedkeys "4"''; + "k" = ''feedkeys "4"''; + "h" = ''feedkeys "4"''; + "l" = ''feedkeys "4"''; + + "J" = ''feedkeys ""''; + "K" = ''feedkeys ""''; + "H" = ''feedkeys ""''; + "L" = ''feedkeys ""''; + + "y" = ''zoom in''; + "+" = ''feedkeys "yyy"''; + "*" = ''feedkeys "y"''; + + "x" = ''zoom out''; + "-" = ''feedkeys "xxx"''; + "_" = ''feedkeys "x"''; + + "n" = ''navigate next''; + "p" = ''navigate previous''; + }; + }; +} + + + + diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..bdb091c --- /dev/null +++ b/flake.lock @@ -0,0 +1,202 @@ +{ + "nodes": { + "cachix": { + "locked": { + "lastModified": 1635350005, + "narHash": "sha256-tAMJnUwfaDEB2aa31jGcu7R7bzGELM9noc91L2PbVjg=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "1c1f5649bb9c1b0d98637c8c365228f57126f361", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-20.09", + "repo": "nixpkgs", + "type": "github" + } + }, + "firefox": { + "inputs": { + "cachix": "cachix", + "flake-compat": "flake-compat", + "lib-aggregate": "lib-aggregate", + "mozilla": "mozilla", + "nixpkgs": "nixpkgs" + }, + "locked": { + "lastModified": 1698022509, + "narHash": "sha256-6cZh1c4i+AH0ROeyoAGqYDvF5Vo2xkb9pQsimgNuCng=", + "owner": "nix-community", + "repo": "flake-firefox-nightly", + "rev": "5d544a9b5cefec53621bf3688f2277bb6c0293a4", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "flake-firefox-nightly", + "type": "github" + } + }, + "flake-compat": { + "locked": { + "lastModified": 1688025799, + "narHash": "sha256-ktpB4dRtnksm9F5WawoIkEneh1nrEvuxb5lJFt1iOyw=", + "owner": "nix-community", + "repo": "flake-compat", + "rev": "8bf105319d44f6b9f0d764efa4fdef9f1cc9ba1c", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1694529238, + "narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "ff7b65b44d01cf9ba6a71320833626af21126384", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "home-manager": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1695108154, + "narHash": "sha256-gSg7UTVtls2yO9lKtP0yb66XBHT1Fx5qZSZbGMpSn2c=", + "owner": "nix-community", + "repo": "home-manager", + "rev": "07682fff75d41f18327a871088d20af2710d4744", + "type": "github" + }, + "original": { + "owner": "nix-community", + "ref": "release-23.05", + "repo": "home-manager", + "type": "github" + } + }, + "lib-aggregate": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs-lib": "nixpkgs-lib" + }, + "locked": { + "lastModified": 1697976504, + "narHash": "sha256-sU8q83TEaafIe5d7L6Dc2alRhWT898aB0+6EXcfao1I=", + "owner": "nix-community", + "repo": "lib-aggregate", + "rev": "2e96d2f9d80f80bd22cd7c603985f2b03cf186fc", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "lib-aggregate", + "type": "github" + } + }, + "mozilla": { + "flake": false, + "locked": { + "lastModified": 1695805681, + "narHash": "sha256-1ElPLD8eFfnuIk0G52HGGpRtQZ4QPCjChRlEOfkZ5ro=", + "owner": "mozilla", + "repo": "nixpkgs-mozilla", + "rev": "6eabade97bc28d707a8b9d82ad13ef143836736e", + "type": "github" + }, + "original": { + "owner": "mozilla", + "repo": "nixpkgs-mozilla", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1697723726, + "narHash": "sha256-SaTWPkI8a5xSHX/rrKzUe+/uVNy6zCGMXgoeMb7T9rg=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "7c9cc5a6e5d38010801741ac830a3f8fd667a7a0", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs-lib": { + "locked": { + "lastModified": 1697935651, + "narHash": "sha256-qOfWjQ2JQSQL15KLh6D7xQhx0qgZlYZTYlcEiRuAMMw=", + "owner": "nix-community", + "repo": "nixpkgs.lib", + "rev": "e1e11fdbb01113d85c7f41cada9d2847660e3902", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixpkgs.lib", + "type": "github" + } + }, + "nixpkgs_2": { + "locked": { + "lastModified": 1698060352, + "narHash": "sha256-c7Thcf2xYTmB4uJpPdb07sPQOIVJWuyjjOfhE4RKq28=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "f4d73aae0f51a1ea3161fc97bf05c683d69bf81c", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "release-23.05", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "firefox": "firefox", + "home-manager": "home-manager", + "nixpkgs": "nixpkgs_2" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..a4e9a1c --- /dev/null +++ b/flake.nix @@ -0,0 +1,36 @@ +{ + description = "Sebastian (c2vi)'s NixOS"; + + inputs = { + #nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + nixpkgs.url = "github:NixOS/nixpkgs/release-23.05"; + firefox.url = "github:nix-community/flake-firefox-nightly"; + + home-manager = { + url = "github:nix-community/home-manager/release-23.05"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + + nix-doom-emacs.url = "github:nix-community/nix-doom-emacs"; + }; + + outputs = let + confDir = "/home/me/work/config"; + workDir = "/home/me/work"; + secretsDir = "/home/me/.mysecrets"; + persistentDir = "/home/me/work/app-data"; + in + { self, nixpkgs, ... }@inputs: { + nixosConfigurations = { + + "c2vi-main" = nixpkgs.lib.nixosSystem { + system = "x86_64-linux"; + + specialArgs = [ inputs confDir workDir ]; + modules = [ + ./hosts/main.nix + ]; + }; + }; + }; +} diff --git a/hardware/my-hp-laptop.nix b/hardware/my-hp-laptop.nix new file mode 100644 index 0000000..a802ca2 --- /dev/null +++ b/hardware/my-hp-laptop.nix @@ -0,0 +1,39 @@ +# Do not modify this file! It was generated by ‘nixos-generate-config’ +# and may be overwritten by future invocations. Please make changes +# to /etc/nixos/configuration.nix instead. +{ config, lib, pkgs, modulesPath, ... }: + +{ + imports = + [ (modulesPath + "/installer/scan/not-detected.nix") + ]; + + boot.initrd.availableKernelModules = [ "xhci_pci" "ahci" "nvme" "usbhid" "usb_storage" "uas" "sd_mod" "sdhci_pci" ]; + boot.initrd.kernelModules = [ "dm-snapshot" ]; + boot.kernelModules = [ "kvm-intel" ]; + boot.extraModulePackages = [ ]; + + fileSystems."/" = + { device = "/dev/disk/by-uuid/356c7b23-71ab-4a01-b700-adbb672bec3e"; + fsType = "btrfs"; + }; + + fileSystems."/boot" = + { device = "/dev/disk/by-uuid/2588-2509"; + fsType = "vfat"; + }; + + swapDevices = [ ]; + + # Enables DHCP on each ethernet and wireless interface. In case of scripted networking + # (the default) this is the recommended approach. When using systemd-networkd it's + # still possible to use this option, but it's recommended to use it in conjunction + # with explicit per-interface declarations with `networking.interfaces..useDHCP`. + networking.useDHCP = lib.mkDefault true; + # networking.interfaces.enp1s0.useDHCP = lib.mkDefault true; + # networking.interfaces.wlp2s0.useDHCP = lib.mkDefault true; + + nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux"; + powerManagement.cpuFreqGovernor = lib.mkDefault "powersave"; + hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware; +} diff --git a/hosts/main.nix b/hosts/main.nix new file mode 100644 index 0000000..ce05dca --- /dev/null +++ b/hosts/main.nix @@ -0,0 +1,236 @@ + +{ pkgs, lib, workDir, confDir, ... }: +{ + + # https://bugzilla.kernel.org/show_bug.cgi?id=110941 + # ??????????? TODO + # boot.kernelParams = [ "intel_pstate=no_hwp" ]; + + # Supposedly better for the SSD. + # ??????????? TODO + # fileSystems."/".options = [ "noatime" "nodiratime" "discard" ]; + + +############################# BOOT ############################# +# boot + + # Setup keyfile + boot.initrd.secrets = { + "/crypto_keyfile.bin" = null; + }; + + fileSystems."/home/me/work" = + { + #label = "work"; + device = "/dev/disk/by-uuid/fd3c6393-b6fd-4065-baf9-5690eb6ebbed"; + fsType = "btrfs"; + neededForBoot = false; + }; + + + # Use the GRUB 2 boot loader. + boot.loader.grub = { + enable = true; + version = 2; + device = "nodev"; + efiSupport = true; + extraConfig = '' + set timeout=1 + ''; + }; + boot.loader.efi.canTouchEfiVariables = true; + + boot.initrd.luks.devices = { + root = { + #name = "root"; + device = "/dev/disk/by-uuid/142d2d21-2998-4eb7-9853-ab6554ba061f"; + preLVM = true; + allowDiscards = true; + }; + }; + + +############################# MISC ############################# +# misc + + + nixpkgs.config.permittedInsecurePackages = [ + "electron-24.8.6" + ]; + + fileSystems."/tmp" = { + fsType = "tmpfs"; + device = "tmpfs"; + options = [ "nosuid" "nodev" "relatime" "size=14G" ]; + }; + + +security.polkit.enable = true; +networking.firewall.enable = true; +networking.firewall.allowPing = true; +services.samba.openFirewall = true; + +# samba +services.samba-wsdd.enable = true; # make shares visible for windows 10 clients +networking.firewall.allowedTCPPorts = [ + 5357 # wsdd +]; +networking.firewall.allowedUDPPorts = [ + 3702 # wsdd +]; +services.samba = { + enable = true; + securityType = "user"; + extraConfig = '' + security = user + map to guest = bad user + guest account = me + + server role = standalone server + workgroup = WORKGROUP + ''; + shares = { + rpi_schule = { + path = "${workDir}/rpi-schule/"; + "guest ok" = "yes"; + "read only" = "no"; + public = "yes"; + writable = "yes"; + printable = "no"; + comment = "share for rpi in school wlan"; + }; + + share = { + comment = "share for sharing stuff"; + path = "${workDir}/share"; + public = "yes"; + "guest ok" = "yes"; + "read only" = "no"; + writable = "yes"; + }; + }; +}; +############### + + + + nix.settings.experimental-features = [ "nix-command" "flakes" ]; + security.sudo.wheelNeedsPassword = false; + + virtualisation.libvirtd.enable = true; + + programs.dconf.enable = true; + system.activationScripts.setupLibvirt = lib.stringAfter [ "var" ] '' + ln -nsf ${workDir}/vm/libvirt/my-image-pool.xml /var/lib/libvirt/storage/my-image-pool.xml + ln -nsf ${workDir}/vm/qemu/* /var/lib/libvirt/qemu/ + + # there is no /bin/bash + # https://discourse.nixos.org/t/add-bin-bash-to-avoid-unnecessary-pain/5673 + ln -nsf /run/current-system/sw/bin/bash /bin/bash + ''; + + environment.etc.profile.text = '' +export PATH=$PATH:${confDir}/mybin + ''; + + modules.battery_monitor.enable = true; + + xdg.portal = { + enable = true; + extraPortals = [ + #pkgs.xdg-desktop-portal-gtk + pkgs.xdg-desktop-portal-termfilechooser + ]; + }; + + networking.hostName = "c2vi-main"; # Define your hostname. + networking.networkmanager.enable = true; # Easiest to use and most distros use this by default. + services.blueman.enable = true; + hardware.bluetooth.enable = true; + + + ################ + # swap and hibernate + + swapDevices = [ { device = "/dev/lvm0/swap"; } ]; + boot.resumeDevice = "/dev/lvm0/swap"; + services.logind = { + extraConfig = '' + HandlePowerKey=suspend-then-hibernate + ''; + lidSwitch = "suspend-then-hibernate"; + lidSwitchExternalPower = "suspend-then-hibernate"; + lidSwitchDocked = "ignore"; + }; + systemd.sleep.extraConfig = '' + HibernateDelaySec=2h + HibernateMode=shutdown + ''; + + # Enable the X11 windowing system. + services.xserver = { + enable = true; + displayManager = { + defaultSession = "none+xmonad"; + sessionCommands = '' + xmobar ${confDir}/xmonad/xmobar.hs & + + # aparently needed, so that xmonad works + sleep 2 && \ + ${pkgs.xorg.xmodmap}/bin/xmodmap \ + -e "clear control" \ + -e "clear mod1" \ + -e "keycode 64 = Control_L" \ + -e "keycode 37 = Alt_L" \ + -e "add control = Control_L" \ + -e "add mod1 = Alt_L" \ + & + + ''; + }; + + displayManager.lightdm = { + greeters.enso = { + enable = true; + blur = true; + extraConfig = '' + default-wallpaper=/usr/share/streets_of_gruvbox.png + ''; + }; + }; + layout = "at"; + }; + + # Configure keymap in X11 + # services.xserver.xkbOptions = "eurosign:e,caps:escape"; + + # Enable CUPS to print documents. + # services.printing.enable = true; + + # Enable sound. + sound.enable = true; + hardware.pulseaudio.enable = true; + + # Enable touchpad support (enabled default in most desktopManager). + services.xserver.libinput.enable = true; + + # List packages installed in system profile. To search, run: + # $ nix search wget + environment.systemPackages = with pkgs; [ + vim # Do not forget to add an editor to edit configuration.nix! + wget + xorg.xmodmap + bluez + ]; + + # This value determines the NixOS release from which the default + # settings for stateful data, like file locations and database versions + # on your system were taken. It's perfectly fine and recommended to leave + # this value at the release version of the first install of this system. + # Before changing this value read the documentation for this option + # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html). + system.stateVersion = "23.05"; # Did you read the comment? + +} + + diff --git a/hosts/phone/stuff.md b/hosts/phone/stuff.md new file mode 100644 index 0000000..f0bdf26 --- /dev/null +++ b/hosts/phone/stuff.md @@ -0,0 +1,3 @@ + +- build android with nix flakes +nix flake init -t github:danielfullmer/robotnix diff --git a/misc/xmobar.hs b/misc/xmobar.hs new file mode 100644 index 0000000..fc33aae --- /dev/null +++ b/misc/xmobar.hs @@ -0,0 +1,74 @@ +Config { + + -- appearance + font = "xft:Bitstream Vera Sans Mono:size=15:bold:antialias=true" + , bgColor = "black" + , fgColor = "#646464" + , position = Top + , border = BottomB + , borderColor = "#646464" + + -- layout + , sepChar = "%" -- delineator between plugin names and straight text + , alignSep = "}{" -- separator between left-right alignment + , template = "HI | %dynnetwork% }{ %battery% | %date%" + --, template = "%battery% | %multicpu% | %coretemp% | %memory% | %dynnetwork% }{ %RJTT% | %date% || %kbd% " + --, template = "%battery% | %multicpu% | %coretemp% | %memory% | %dynnetwork% }{ %RJTT% | %date% || %kbd% " + + -- general behavior + , lowerOnStart = True -- send to bottom of window stack on start + , hideOnStart = False -- start with window unmapped (hidden) + , allDesktops = True -- show on all desktops + , overrideRedirect = True -- set the Override Redirect flag (Xlib) + , pickBroadest = False -- choose widest display (multi-monitor) + , persistent = True -- enable/disable hiding (True = disabled) + + -- plugins + -- Numbers can be automatically colored according to their value. xmobar + -- decides color based on a three-tier/two-cutoff system, controlled by + -- command options: + -- --Low sets the low cutoff + -- --High sets the high cutoff + -- + -- --low sets the color below --Low cutoff + -- --normal sets the color between --Low and --High cutoffs + -- --High sets the color above --High cutoff + -- + -- The --template option controls how the plugin is displayed. Text + -- color can be set by enclosing in tags. For more details + -- see http://projects.haskell.org/xmobar/#system-monitor-plugins. + , commands = + [ + -- network + Run DynNetwork [ "--template" , ": kB/s|kB/s" + , "--Low" , "1000" -- units: B/s + , "--High" , "5000" -- units: B/s + , "--low" , "darkgreen" + , "--normal" , "darkorange" + , "--high" , "darkred" + ] 10 + + -- batery + , Run Battery [ "--template" , "Batt: " + , "--Low" , "10" -- units: % + , "--High" , "80" -- units: % + , "--low" , "darkred" + , "--normal" , "darkorange" + , "--high" , "darkgreen" + + , "--" -- battery specific options + -- discharging status + , "-o" , "% ()" + -- AC "on" status + , "-O" , "Charging" + -- charged status + , "-i" , "Charged" + ] 50 + + -- time and date indicator + -- (%F = y-m-d date, %a = day of week, %T = h:m:s time) + , Run Date "%F (%a) %T" "date" 10 + + ] + +} diff --git a/misc/xmonad.hs b/misc/xmonad.hs new file mode 100644 index 0000000..23336e4 --- /dev/null +++ b/misc/xmonad.hs @@ -0,0 +1,364 @@ +-- xmonad example config file. +-- +-- A template showing all available configuration hooks, +-- and how to override the defaults in your own xmonad.hs conf file. +-- +-- Normally, you'd only override those defaults you care about. +-- + +import XMonad +import Data.Monoid +import System.Exit + +--for xmobar +import XMonad.Hooks.DynamicLog +import XMonad.Hooks.StatusBar +import XMonad.Hooks.StatusBar.PP +import XMonad.Hooks.SetWMName +import XMonad.Hooks.EwmhDesktops + + +import qualified XMonad.StackSet as W +import qualified Data.Map as M + +-- The preferred terminal program, which is used in a binding below and by +-- certain contrib modules. +-- +myTerminal = "alacritty" + +-- Whether focus follows the mouse pointer. +myFocusFollowsMouse :: Bool +myFocusFollowsMouse = True + +-- Whether clicking on a window to focus also passes the click to the window +myClickJustFocuses :: Bool +myClickJustFocuses = False + +-- Width of the window border in pixels. +-- +myBorderWidth = 2 + +-- modMask lets you specify which modkey you want to use. The default +-- is mod1Mask ("left alt"). You may also consider using mod3Mask +-- ("right alt"), which does not conflict with emacs keybindings. The +-- "windows key" is usually mod4Mask. +-- +myModMask = mod4Mask + +-- The default number of workspaces (virtual screens) and their names. +-- By default we use numeric strings, but any string may be used as a +-- workspace name. The number of workspaces is determined by the length +-- of this list. +-- +-- A tagging example: +-- +-- > workspaces = ["web", "irc", "code" ] ++ map show [4..9] +-- +myWorkspaces = ["1","2","3","4","5","6","7","8","9"] + +-- Border colors for unfocused and focused windows, respectively. +-- +myNormalBorderColor = "#dddddd" +myFocusedBorderColor = "#ff0000" +-- myFocusedBorderColor = "#68cedc" + +------------------------------------------------------------------------ +-- Key bindings. Add, modify or remove key bindings here. +-- +myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $ + + [ + + -- launch a terminal + ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf), + + -- enable keyboard + --((button2), spawn "xinput enable 17"), + --((modm .|. button2, \w -> focus w >> windows W.shiftMaster), + + + -- player next + ((modm, xK_n), spawn "playerctl next"), + -- player previous + ((modm .|. shiftMask, xK_n), spawn "playerctl previous"), + -- player play-pause + ((modm , xK_c), spawn "playerctl play-pause"), + -- player volume up + ((modm , xK_v), spawn "amixer set Master 3%+"), + -- player volume down + ((modm .|. shiftMask, xK_v), spawn "amixer set Master 3%-"), + + -- xrandr + ((modm .|. shiftMask, xK_d), spawn "xrandr --output eDP-1 --off"), + + ((modm .|. shiftMask, xK_f), spawn "bash -c \"kill -9 $(pgrep firefox)\""), + + ((modm , xK_d), spawn "xrandr --output eDP-1 --auto"), + + + -- launch dmenu + ((modm, xK_p ), spawn "nice -n 7 rofi -show run"), + + -- close focused window + ((modm .|. shiftMask, xK_c ), kill), + + -- Rotate through the available layout algorithms + ((modm, xK_space ), sendMessage NextLayout), + + -- Reset the layouts on the current workspace to default + ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf), + + -- Resize viewed windows to the correct size + --((modm, xK_n ), refresh), + + -- Move focus to the next window + ((modm, xK_Tab ), windows W.focusDown), + + -- Move focus to the next window + ((modm, xK_j ), windows W.focusDown), + + -- Move focus to the previous window + ((modm, xK_k ), windows W.focusUp ), + + -- Move focus to the master window + --((modm, xK_m ), windows W.focusMaster ), + + -- Swap the focused window and the master window + ((modm, xK_Return), windows W.swapMaster), + + -- Swap the focused window with the next window + ((modm .|. shiftMask, xK_j ), windows W.swapDown ), + + -- Swap the focused window with the previous window + ((modm .|. shiftMask, xK_k ), windows W.swapUp ), + + -- Shrink the master area + ((modm, xK_h ), sendMessage Shrink), + + -- Expand the master area + ((modm, xK_l ), sendMessage Expand), + + -- Push window back into tiling + ((modm, xK_t ), withFocused $ windows . W.sink), + + -- Increment the number of windows in the master area + ((modm , xK_comma ), sendMessage (IncMasterN 1)), + + -- Deincrement the number of windows in the master area + ((modm , xK_period), sendMessage (IncMasterN (-1))), + + -- Toggle the status bar gap + -- Use this binding with avoidStruts from Hooks.ManageDocks. + -- See also the statusBar function from Hooks.DynamicLog. + -- + -- , ((modm , xK_b ), sendMessage ToggleStruts) + + -- Quit xmonad + ((modm .|. shiftMask, xK_q ), io exitSuccess), + + -- Restart xmonad + ((modm , xK_q ), spawn "xmonad --recompile; xmonad --restart") + + -- Run xmessage with a summary of the default keybindings (useful for beginners) + --, ((modm .|. shiftMask, xK_slash ), xmessage help) + ] + ++ + + -- + -- mod-[1..9], Switch to workspace N + -- mod-shift-[1..9], Move client to workspace N + -- + [((m .|. modm, k), windows $ f i) + | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9] + , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] + ++ + + -- + -- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3 + -- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3 + -- + [((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f)) + | (key, sc) <- zip [xK_w, xK_e, xK_r] [0..] + , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]] + + +------------------------------------------------------------------------ +-- Mouse bindings: default actions bound to mouse events +-- +myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList + + -- mod-button1, Set the window to floating mode and move by dragging + [ ((modm, button1), \w -> focus w >> mouseMoveWindow w + >> windows W.shiftMaster) + + -- mod-button2, Raise the window to the top of the stack + -- , ((button2), spawn "xinput enable 17") + + -- mod-button3, Set the window to floating mode and resize by dragging + , ((modm, button3), \w -> focus w >> mouseResizeWindow w + >> windows W.shiftMaster) + + -- you may also bind events to the mouse scroll wheel (button4 and button5) + ] + +------------------------------------------------------------------------ +-- Layouts: + +-- You can specify and transform your layouts by modifying these values. +-- If you change layout bindings be sure to use 'mod-shift-space' after +-- restarting (with 'mod-q') to reset your layout state to the new +-- defaults, as xmonad preserves your old layout settings by default. +-- +-- The available layouts. Note that each layout is separated by |||, +-- which denotes layout choice. +-- +myLayout = tiled ||| Full + where + -- default tiling algorithm partitions the screen into two panes + tiled = Tall nmaster delta ratio + + -- The default number of windows in the master pane + nmaster = 1 + + -- Default proportion of screen occupied by master pane + ratio = 1/2 + + -- Percent of screen to increment by when resizing panes + delta = 3/100 + +------------------------------------------------------------------------ +-- Window rules: + +-- Execute arbitrary actions and WindowSet manipulations when managing +-- a new window. You can use this to, for example, always float a +-- particular program, or have a client always appear on a particular +-- workspace. +-- +-- To find the property name associated with a program, use +-- > xprop | grep WM_CLASS +-- and click on the client you're interested in. +-- +-- To match on the WM_NAME, you can use 'title' in the same way that +-- 'className' and 'resource' are used below. +-- +myManageHook = composeAll + [ + className =? "MPlayer" --> doFloat, + className =? "Gimp" --> doFloat, + resource =? "desktop_window" --> doIgnore, + resource =? "kdesktop" --> doIgnore + ] + +------------------------------------------------------------------------ +-- Event handling + +-- * EwmhDesktops users should change this to ewmhDesktopsEventHook +-- +-- Defines a custom handler function for X Events. The function should +-- return (All True) if the default handler is to be run afterwards. To +-- combine event hooks use mappend or mconcat from Data.Monoid. +-- +myEventHook = ewmhFullscreen + +------------------------------------------------------------------------ +-- Status bars and logging + +-- Perform an arbitrary action on each internal state change or X event. +-- See the 'XMonad.Hooks.DynamicLog' extension for examples. +-- +myLogHook = return () + +------------------------------------------------------------------------ +-- Startup hook + +-- Perform an arbitrary action each time xmonad starts or is restarted +-- with mod-q. Used by, e.g., XMonad.Layout.PerWorkspace to initialize +-- per-workspace layout choices. +-- +myStartupHook = do + spawn "echo hiiiiiiiiiiiiiiiiiiiiiiiiiiii | sudo tee -a /dev/kmsg" + spawn "bash ~/work/virtchord/run &" + spawn "xset r rate 130 85" + -- spawn "sudo swapon /swapfile" + spawn "setxkbmap de" + setWMName "LG3D" + + +main = xmonad $ xmobarProp $ myConfig + + +myConfig = ewmh def { + -- simple stuff + terminal = myTerminal, + focusFollowsMouse = myFocusFollowsMouse, + clickJustFocuses = myClickJustFocuses, + borderWidth = myBorderWidth, + modMask = myModMask, + workspaces = myWorkspaces, + normalBorderColor = myNormalBorderColor, + focusedBorderColor = myFocusedBorderColor, + + -- key bindings + keys = myKeys, + mouseBindings = myMouseBindings, + + -- hooks, layouts + layoutHook = myLayout, + manageHook = myManageHook, + handleEventHook = handleEventHook def <+> fullscreenEventHook, + logHook = myLogHook, + startupHook = myStartupHook + } + + +-- | Finally, a copy of the default bindings in simple textual tabular format. +help :: String +help = unlines ["The default modifier key is 'alt'. Default keybindings:", + "", + "-- launching and killing programs", + "mod-Shift-Enter Launch xterminal", + "mod-p Launch dmenu", + "mod-Shift-p Launch gmrun", + "mod-Shift-c Close/kill the focused window", + "mod-Space Rotate through the available layout algorithms", + "mod-Shift-Space Reset the layouts on the current workSpace to default", + "mod-n Resize/refresh viewed windows to the correct size", + "mod-Shift-/ Show this help message with the default keybindings", + "", + "-- move focus up or down the window stack", + "mod-Tab Move focus to the next window", + "mod-Shift-Tab Move focus to the previous window", + "mod-j Move focus to the next window", + "mod-k Move focus to the previous window", + "mod-m Move focus to the master window", + "", + "-- modifying the window order", + "mod-Return Swap the focused window and the master window", + "mod-Shift-j Swap the focused window with the next window", + "mod-Shift-k Swap the focused window with the previous window", + "", + "-- resizing the master/slave ratio", + "mod-h Shrink the master area", + "mod-l Expand the master area", + "", + "-- floating layer support", + "mod-t Push window back into tiling; unfloat and re-tile it", + "", + "-- increase or decrease number of windows in the master area", + "mod-comma (mod-,) Increment the number of windows in the master area", + "mod-period (mod-.) Deincrement the number of windows in the master area", + "", + "-- quit, or restart", + "mod-Shift-q Quit xmonad", + "mod-q Restart xmonad", + "mod-[1..9] Switch to workSpace N", + "", + "-- Workspaces & screens", + "mod-Shift-[1..9] Move client to workspace N", + "mod-{w,e,r} Switch to physical/Xinerama screens 1, 2, or 3", + "mod-Shift-{w,e,r} Move client to screen 1, 2, or 3", + "", + "-- Mouse bindings: default actions bound to mouse events", + "mod-button1 Set the window to floating mode and move by dragging", + "mod-button2 Raise the window to the top of the stack", + "mod-button3 Set the window to floating mode and resize by dragging"] diff --git a/mods/battery_monitor.nix b/mods/battery_monitor.nix new file mode 100644 index 0000000..f538fb8 --- /dev/null +++ b/mods/battery_monitor.nix @@ -0,0 +1,53 @@ +{ config, pkgs, lib, ... }: + +# Regularly check the battery status and send a notification when it discharges +# below certain thresholds. +# Implemented by calling the `acpi` program regularly. This is the simpler and +# safer approach because the battery might not send discharging events. + +let conf = config.modules.battery_monitor; + +in { + options.modules.battery_monitor = with lib; { + enable = mkEnableOption "battery_monitor"; + }; + + config = lib.mkIf conf.enable { + # Regularly check battery status + systemd.user.services.battery_monitor = { + wants = [ "display-manager.service" ]; + wantedBy = [ "graphical-session.target" ]; + script = '' + count_10=0 + prev_val=100 + check () { [[ $1 -ge $val ]] && [[ $1 -lt $prev_val ]]; } + notify () { + ${pkgs.libnotify}/bin/notify-send -a Battery "$@" \ + -h "int:value:$val" "Discharging" "$val%, $remaining" + } + while true; do + IFS=: read _ bat0 < <(${pkgs.acpi}/bin/acpi -b) + IFS=\ , read status val remaining <<<"$bat0" + val=''${val%\%} + if [[ $status = Discharging ]]; then + echo "$val%, $remaining" + + if check 20; then notify + elif check 15 || [[ $val -le 7 ]]; then notify -u critical + elif [[ $val -le 4 ]] + then + ${pkgs.notify}/bin/notify-send -a Hibernate soon... + sleep 10 + ${pkgs.notify}/bin/notify-send -a Hibernate NOW + sudo systemctl hibernate + fi + fi + prev_val=$val + # Sleep longer when battery is high to save CPU + if [[ $val -gt 30 ]]; then sleep 10m; elif [[ $val -ge 20 ]]; then sleep 5m; else sleep 1m; fi + done + ''; + }; + + }; +} diff --git a/mods/my-nixpkgs-overlay.nix b/mods/my-nixpkgs-overlay.nix new file mode 100644 index 0000000..1492e17 --- /dev/null +++ b/mods/my-nixpkgs-overlay.nix @@ -0,0 +1,11 @@ + +{ pkgs, confDir, inputs, ... }: +{ + nixpkgs.overlays = [ + { + localPacketTracer8 = (pkgs.callPackage ../../prebuilt/packetTracer/default.nix {confDir = confDir;}); + xdg-desktop-portal-termfilechooser = (pkgs.callPackage ../../mods/xdg-desktop-portal-termfilechooser/default.nix {}); + firefox = inputs.firefox.packages.${pkgs.system}.firefox-nightly-bin; + } + ]; +} diff --git a/mods/xdg-desktop-portal-termfilechooser/default.nix b/mods/xdg-desktop-portal-termfilechooser/default.nix new file mode 100644 index 0000000..f0c5f28 --- /dev/null +++ b/mods/xdg-desktop-portal-termfilechooser/default.nix @@ -0,0 +1,86 @@ + +{ lib +, stdenv +, fetchFromGitHub +, meson +, pkgconfig +, inih +, systemd +, scdoc +, ninja +, pkgs +, alacritty +}: + +stdenv.mkDerivation rec { + pname = "xdg-desktop-portal-termfilechooser"; + version = "0.0.0"; + + src = fetchFromGitHub { + owner = "GermainZ"; + repo = "xdg-desktop-portal-termfilechooser"; + rev = "71dc7ab06751e51de392b9a7af2b50018e40e062"; + hash = "sha256-645hoLhQNncqfLKcYCgWLbSrTRUNELh6EAdgUVq3ypM="; + }; + + #doCheck = true; + #doUnpack = true; + + #passthru.tests.version = + #testVersion { package = hello; }; + + nativeBuildInputs = [ + meson + pkgconfig + inih + systemd + scdoc + ninja + ]; + + buildInputs = [ + systemd + ]; + + patches = [ + ./xdg-desktop-portal-termfilechooser-add-x11.patch + ./test.patch + ./test2.patch + ./meson-build.patch + ./lf-wrapper.patch + + ]; + + mesonFlags = [ + "-Dsd-bus-provider=libsystemd" + ]; + + installPhase = '' + ninja install + ''; + + postConfigure = '' + substituteInPlace ../src/core/config.c --replace '#define FILECHOOSER_DEFAULT_CMD "/usr/share/xdg-desktop-portal-termfilechooser/ranger-wrapper.sh"' '#define FILECHOOSER_DEFAULT_CMD "${placeholder "out"}/share/xdg-desktop-portal-termfilechooser/lf-wrapper.sh"' + + ls ../contrib + substituteInPlace ../contrib/lf-wrapper.sh --replace '#CCCMMMDDD' '${alacritty}/bin/alacritty' + + echo "###### start" + cat ../src/core/config.c + echo "###### end" + + ''; + #exit 1 + #substituteInPlace ../src/core/config.c --replace '#define FILECHOOSER_DEFAULT_DIR "/tmp"' '#define FILECHOOSER_DEFAULT_DIR "${placeholder "out"}/share/xdg-desktop-portal/portals/termfilechooser.portal"' + + meta = with lib; { + description = "A xdg portal, that let's you use your favourite terminal file chooser to choose files acroos all applications"; + longDescription = "A long description"; + homepage = "https://github.com/GermainZ/xdg-desktop-portal-termfilechooser"; + license = licenses.mit; + maintainers = [ maintainers.eelco ]; + platforms = platforms.all; + }; +} + + diff --git a/mods/xdg-desktop-portal-termfilechooser/flake.nix b/mods/xdg-desktop-portal-termfilechooser/flake.nix new file mode 100644 index 0000000..81a5755 --- /dev/null +++ b/mods/xdg-desktop-portal-termfilechooser/flake.nix @@ -0,0 +1,78 @@ +{ + description = "xdg-desktop-portal-termfilechooser"; + + #inputs = { + #nixpkgs.url = "github:NixOS/nixpkgs/release-23.05"; + #}; + + outputs = { self, nixpkgs }: { + packages.x86_64-linux.default = with nixpkgs.x86_64.pkgs; pkgs.mkDerivation rec { + pname = "xdg-desktop-portal-termfilechooser"; + version = "0.0.0"; + + src = fetchFromGitHub { + owner = "GermainZ"; + repo = "xdg-desktop-portal-termfilechooser"; + rev = "71dc7ab06751e51de392b9a7af2b50018e40e062"; + hash = "sha256-645hoLhQNncqfLKcYCgWLbSrTRUNELh6EAdgUVq3ypM="; + }; + + #doCheck = true; + #doUnpack = true; + + #passthru.tests.version = + #testVersion { package = hello; }; + + nativeBuildInputs = [ + meson + pkgconfig + inih + systemd + scdoc + ninja + ]; + + buildInputs = [ + systemd + ]; + + patches = [ + ./xdg-desktop-portal-termfilechooser-add-x11.patch + ./test.patch + ./test2.patch + ./meson-build.patch + ./lf-wrapper.patch + ]; + + mesonFlags = [ + "-Dsd-bus-provider=libsystemd" + ]; + + installPhase = '' + ninja install + ''; + + postConfigure = '' + substituteInPlace ../src/core/config.c --replace '#define FILECHOOSER_DEFAULT_CMD "/usr/share/xdg-desktop-portal-termfilechooser/ranger-wrapper.sh"' '#define FILECHOOSER_DEFAULT_CMD "${placeholder "out"}/share/xdg-desktop-portal-termfilechooser/lf-wrapper.sh"' + + ls ../contrib + substituteInPlace ../contrib/lf-wrapper.sh --replace '#CCCMMMDDD' '${alacritty}/bin/alacritty' + + echo "###### start" + cat ../src/core/config.c + echo "###### end" + + ''; + #exit 1 + #substituteInPlace ../src/core/config.c --replace '#define FILECHOOSER_DEFAULT_DIR "/tmp"' '#define FILECHOOSER_DEFAULT_DIR "${placeholder "out"}/share/xdg-desktop-portal/portals/termfilechooser.portal"' + + meta = with lib; { + description = "A xdg portal, that let's you use your favourite terminal file chooser to choose files acroos all applications"; + longDescription = "A long description"; + homepage = "https://github.com/GermainZ/xdg-desktop-portal-termfilechooser"; + license = licenses.mit; + maintainers = [ maintainers.eelco ]; + platforms = platforms.all; + }; + }; + } diff --git a/mods/xdg-desktop-portal-termfilechooser/lf-wrapper.patch b/mods/xdg-desktop-portal-termfilechooser/lf-wrapper.patch new file mode 100644 index 0000000..8c854c0 --- /dev/null +++ b/mods/xdg-desktop-portal-termfilechooser/lf-wrapper.patch @@ -0,0 +1,42 @@ +diff --git a/contrib/lf-wrapper.sh b/contrib/lf-wrapper.sh +new file mode 100755 +index 0000000..9b9a20d +--- /dev/null ++++ b/contrib/lf-wrapper.sh +@@ -0,0 +1,36 @@ ++#!/bin/sh ++# This wrapper script is invoked by xdg-desktop-portal-termfilechooser. ++# ++# Inputs: ++# 1. "1" if multiple files can be chosen, "0" otherwise. ++# 2. "1" if a directory should be chosen, "0" otherwise. ++# 3. "0" if opening files was requested, "1" if writing to a file was ++# requested. For example, when uploading files in Firefox, this will be "0". ++# When saving a web page in Firefox, this will be "1". ++# 4. If writing to a file, this is recommended path provided by the caller. For ++# example, when saving a web page in Firefox, this will be the recommended ++# path Firefox provided, such as "~/Downloads/webpage_title.html". ++# Note that if the path already exists, we keep appending "_" to it until we ++# get a path that does not exist. ++# 5. The output path, to which results should be written. ++# ++# Output: ++# The script should print the selected paths to the output path (argument #5), ++# one path per line. ++# If nothing is printed, then the operation is assumed to have been canceled. ++ ++multiple="$1" ++directory="$2" ++save="$3" ++path="$4" ++out="$5" ++ ++echo teeeeeeeeeeeeeeeeeeeeeeeeeeest ++read ++ ++#mdolphin ++#alacritty ++#CCCMMMDDD ++ ++ ++exit diff --git a/mods/xdg-desktop-portal-termfilechooser/meson-build.patch b/mods/xdg-desktop-portal-termfilechooser/meson-build.patch new file mode 100644 index 0000000..ed4f846 --- /dev/null +++ b/mods/xdg-desktop-portal-termfilechooser/meson-build.patch @@ -0,0 +1,16 @@ +diff --git a/meson.build b/meson.build +index 8225b6f..f416565 100644 +--- a/meson.build ++++ b/meson.build +@@ -109,6 +109,11 @@ install_data( + install_dir: join_paths(get_option('datadir'), 'xdg-desktop-portal-termfilechooser'), + ) + ++install_data( ++ 'contrib/lf-wrapper.sh', ++ install_dir: join_paths(get_option('datadir'), 'xdg-desktop-portal-termfilechooser'), ++) ++ + scdoc = dependency('scdoc', required: get_option('man-pages'), version: '>= 1.9.7') + if scdoc.found() + man_pages = ['xdg-desktop-portal-termfilechooser.5.scd'] diff --git a/mods/xdg-desktop-portal-termfilechooser/test.patch b/mods/xdg-desktop-portal-termfilechooser/test.patch new file mode 100644 index 0000000..63d036f --- /dev/null +++ b/mods/xdg-desktop-portal-termfilechooser/test.patch @@ -0,0 +1,14 @@ +diff --git a/contrib/ranger-wrapper.sh b/contrib/ranger-wrapper.sh +index 88bc697..b5d3fe0 100755 +--- a/contrib/ranger-wrapper.sh ++++ b/contrib/ranger-wrapper.sh +@@ -25,6 +25,9 @@ save="$3" + path="$4" + out="$5" + ++echo hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii ++read ++ + cmd="/usr/bin/ranger" + termcmd="${TERMCMD:-/usr/bin/kitty}" + diff --git a/mods/xdg-desktop-portal-termfilechooser/test2.patch b/mods/xdg-desktop-portal-termfilechooser/test2.patch new file mode 100644 index 0000000..79c1bd7 --- /dev/null +++ b/mods/xdg-desktop-portal-termfilechooser/test2.patch @@ -0,0 +1,21 @@ +diff --git a/src/filechooser/filechooser.c b/src/filechooser/filechooser.c +index 6cecec6..bd9ba7f 100644 +--- a/src/filechooser/filechooser.c ++++ b/src/filechooser/filechooser.c +@@ -19,6 +19,7 @@ static const char interface_name[] = "org.freedesktop.impl.portal.FileChooser"; + static int exec_filechooser(void *data, bool writing, bool multiple, bool directory, char *path, char ***selected_files, size_t *num_selected_files) { + struct xdpw_state *state = data; + char *cmd_script = state->config->filechooser_conf.cmd; ++ logprint(ERROR, "hiiiiiiiiiiiiiii ... cmd_script: %s", cmd_script); + if (!cmd_script) { + logprint(ERROR, "cmd not specified"); + return -1; +@@ -33,7 +34,7 @@ static int exec_filechooser(void *data, bool writing, bool multiple, bool direct + snprintf(cmd, str_size, "%s %d %d %d \"%s\" \"%s\"", cmd_script, multiple, directory, writing, path, PATH_PORTAL); + + remove(PATH_PORTAL); +- logprint(TRACE, "executing command: %s", cmd); ++ logprint(ERROR, "executing command: %s", cmd); + int ret = system(cmd); + if (ret) { + logprint(ERROR, "could not execute %s: %d", cmd, errno); diff --git a/mods/xdg-desktop-portal-termfilechooser/xdg-desktop-portal-termfilechooser-add-x11.patch b/mods/xdg-desktop-portal-termfilechooser/xdg-desktop-portal-termfilechooser-add-x11.patch new file mode 100644 index 0000000..01e1fce --- /dev/null +++ b/mods/xdg-desktop-portal-termfilechooser/xdg-desktop-portal-termfilechooser-add-x11.patch @@ -0,0 +1,10 @@ +diff --git a/termfilechooser.portal b/termfilechooser.portal +index f072ba0..65f21d8 100644 +--- a/termfilechooser.portal ++++ b/termfilechooser.portal +@@ -1,4 +1,4 @@ + [portal] + DBusName=org.freedesktop.impl.portal.desktop.termfilechooser + Interfaces=org.freedesktop.impl.portal.FileChooser; +-UseIn=i3;wlroots;sway;Wayfire;river;mate;lxde;openbox;unity;pantheon ++UseIn=i3;wlroots;sway;Wayfire;river;mate;lxde;openbox;unity;pantheon;x11 diff --git a/mybin/dim b/mybin/dim new file mode 100755 index 0000000..4ec1827 --- /dev/null +++ b/mybin/dim @@ -0,0 +1,4 @@ +#!/bin/bash + +xinput disable "Logitech Wireless Mouse" + diff --git a/mybin/disp b/mybin/disp new file mode 100755 index 0000000..c776b19 --- /dev/null +++ b/mybin/disp @@ -0,0 +1,5 @@ + +cmd=$1 + +out-default="xrandr --output HDMI-1 --same-as eDP-1 --mode 1920x1080" + diff --git a/mybin/enm b/mybin/enm new file mode 100755 index 0000000..020a2a4 --- /dev/null +++ b/mybin/enm @@ -0,0 +1,4 @@ +#!/bin/bash + +xinput enable "Logitech Wireless Mouse" + diff --git a/mybin/fingre b/mybin/fingre new file mode 100755 index 0000000..699ad95 --- /dev/null +++ b/mybin/fingre @@ -0,0 +1,19 @@ +#!/bin/bash + +v_flag="" +flag="" + +while getopts ':v:' flag; do + case "${flag}" in + v) v_flag="${OPTARG}";; + *) echo "invalid flag" + exit 1 ;; + esac +done + +if [[ "$v_flag" == "" ]] +then + find . -not -type d | xargs grep $@ 2>/dev/null +else + find . -not -type d | grep -v "$v_flag" | xargs grep $@ 2>/dev/null +fi diff --git a/mybin/mdolphin b/mybin/mdolphin new file mode 100755 index 0000000..22a6906 --- /dev/null +++ b/mybin/mdolphin @@ -0,0 +1,5 @@ +#!/bin/bash + +QT_STYLE_OVERRIDE=breeze QT_SCALE_FACTOR=1.3 QT_QPA_PLATFORMTHEME=qt5ct dolphin + + diff --git a/mybin/mshot b/mybin/mshot new file mode 100755 index 0000000..f7b1965 --- /dev/null +++ b/mybin/mshot @@ -0,0 +1,5 @@ +#!/bin/bash + +#gnome-screenshot -ia +flameshot gui + diff --git a/mybin/mvn b/mybin/mvn new file mode 100755 index 0000000..323f3c5 --- /dev/null +++ b/mybin/mvn @@ -0,0 +1,58 @@ +#!/bin/bash + +#revert: + +#svn st | grep ^D | cut -c 9- | sed 's/^/"/' | sed 's/$/"/' | xargs svn revert -R +#svn st | grep ^A | cut -c 9- | sed 's/^/"/' | sed 's/$/"/' | xargs svn revert -R + + +if [ "$1" == "cut" ] +then + cut -c 9- | sed 's/^/"/' | sed 's/$/"/' +fi + + +if [ "$1" == "e" ] +then + if [ "$2" == "" ] + then + export SVN_EDITOR=nvim + echo "DONE: export SVN_EDITOR=nvim" + + else + export SVN_EDITOR=nvim + svn propedit svn:ignore $2 + fi +fi + + +if [ "$1" == "ignore" ] +then + if [ -t 0 ] + then + echo + else + # have a pipe + cat >> ./svn-ignore + fi + # do if no or some pipe ... apply the things in the svn-ignore file + cat ./svn-ignore | tr -d '"' | sed 's/$/\/../' | xargs svn propdel svn:ignore 1>/null + cat ./svn-ignore | tr -d '"' | sed 's\^\./\' | while read p; do + name=$(echo -en "$p" | tr "/" "\n" | tail -n 1) + path=${p%/*} + prop=$(svn propget svn:ignore $path) + svn propset svn:ignore "${prop}"$'\n'"${name}" $path + echo prop: $prop + echo path: $path + done +fi + + +if [ "$1" == "up" ] +then + echo "-----------------------------------------------------------------" + svn st | grep ^? | cut -c 9- | sed 's/^/"/' | sed 's/$/"@/' | xargs svn add + svn st | grep ^! | cut -c 9- | sed 's/^/"/' | sed 's/$/"@/' | xargs svn rm + echo "-----------------------------------------------------------------" + svn ci -m "$2" +fi diff --git a/mybin/ru b/mybin/ru new file mode 100755 index 0000000..c5c167b --- /dev/null +++ b/mybin/ru @@ -0,0 +1,75 @@ +#!/bin/bash + +if [ "$1" == "sync-school" ] +then +~/work/config/rclone/sync-school.sh + + +elif [ "$1" == "mnt-wechner" ] +then +rclone mount --vfs-cache-mode full -vvvv onedrive-school:projekt-autobatterie ~/wechner-mount/ + + +elif [ "$1" == "wstunnel" ] +then +wstunnel -L 55555:127.0.0.1:49388 ws://sebastian.dns.army:49389 + + + +elif [ "$1" == "speed-test-nixos-iso" ] +then +wget "https://dl.t2sde.org/binary/2022/t2-22.6-x86-64-minimal-desktop-gcc-glibc.iso" + + +elif [ "$1" == "p" ] +then +ping orf.at + + +elif [ "$1" == "mnt-files-local" ] +then +sudo mount -t cifs //192.168.1.2/files /home/me/files -o x-gvfs-hide,rw,defaults,nofail,credentials=/home/me/.mysecrets/rpi-share-files,uid=1000,iocharset=utf8,gid=1000 + + + + +elif [ "$1" == "mnt-files-remote" ] +then +sshfs -o default_permissions,idmap=user,uid=1000,gid=1000 files:/home/files/storage/files /home/me/files + + #fusermount -u /home/sebastian/files + #fusermount -u /home/sebastian/lan + + +elif [ "$1" == "mnt-lan-remote" ] +then +sshfs -o default_permissions,idmap=user,uid=1000,gid=1000 files:/home/files/storage/lan /home/me/lan + + +elif [ "$1" == "mnt-lan-local" ] +then +sudo mount -t cifs //192.168.1.2/lan /home/me/lan -o x-gvfs-hide,username=guest,defaults,nofail,guest,uid=1000,gid=1000,iocharset=utf8 + + +elif [ "$1" == "bat" ] +then +now=$(cat /sys/class/power_supply/BAT0/charge_now) +full=$(cat /sys/class/power_supply/BAT0/charge_full) +stat=$(python -c "print( round($now / float($full) *100) )") +echo BAT0 at: ${stat}% + + + +elif [ "$1" == "bstat" ] +then +cat /sys/class/power_supply/BAT0/status + + +elif [ "$1" == "hibernate" ] +then +sudo systemctl hibernate + + +fi + + diff --git a/mybin/song b/mybin/song new file mode 100755 index 0000000..31218c1 --- /dev/null +++ b/mybin/song @@ -0,0 +1,3 @@ +#!/bin/bash + +SONG_CONF_PATH=~/work/things/cool-songs.json ~/scripts/song $@ diff --git a/mybin/songt b/mybin/songt new file mode 100755 index 0000000..cc11c3e --- /dev/null +++ b/mybin/songt @@ -0,0 +1,3 @@ +#!/bin/bash + +SONG_CONF_PATH=~/work/things/touching-songs.json ~/scripts/song $@ diff --git a/mybin/thq b/mybin/thq new file mode 100755 index 0000000..c6cee1b --- /dev/null +++ b/mybin/thq @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 + +DIR = "/home/me/work/things/storage/thq" +FILE = DIR + "/main.json" +EDITOR = "nvim" + +import os +import click +from click_aliases import ClickAliasedGroup + +# python..... +true = True +false = False + +class JSON: + from json import dumps as stringify + from json import loads as parse + + +@click.group(cls=ClickAliasedGroup) +def main(): + pass + +@main.command(aliases=["al"]) +def add_link(): + global data + lnk = input("LINK: ") + new = { + "type": "link", + "val": lnk + } + data.append(new) + +@main.command(aliases=["als"]) +def add_links(): + global data + + lns = [] + while true: + lnk = input("LINK: ") + if lnk == "": + break + else: + lns.append(lnk) + + new = { + "type": "links", + "val": lns + } + data.append(new) + +@main.command(aliases=["ae"]) +def add_edit(): + os.system(f'{EDITOR} {DIR}/edit-file') + with open(f'{DIR}/edit-file', "r") as file: + st = file.read() + + os.remove(f'{DIR}/edit-file') + + new = { + "type": "string", + "val": st + } + data.append(new) + +@main.command(aliases=["af"]) +def add_file(): + global data + + os.system("mv " + file + " " + DIR + "/files") + name = file.split("/")[-1] + print(name) + new = { + "type": "file", + "val": name + } + data.append(new) + + +@main.command(aliases=["a"]) +@click.argument("text", nargs=-1) +def add(text): + global data + + new = { + "type": "string", + "val": " ".join(text) + } + data.append(new) + +@main.command(aliases=["g"]) +def get(): + global data + if len(data) == 0: + print("Nothing to do...") + return + + now = data[0] + with open(f'{DIR}/now.json', "w") as file: + file.write(JSON.stringify(now)) + + data.pop(0) + + if now["type"] == "string": + print("now") + + elif now["type"] == "link": + os.system("firefox " + now["val"]) + + elif now["type"] == "links": + for link in now["val"]: + os.system("firefox " + link) + + elif now["type"] == "file": + print("FILE: " + now["val"]) + #os.system("zath " + now["val"]) + +@main.command(aliases=["ar"]) +def archive_now(): + with open(f'{DIR}/now.json', "r") as file: + now = JSON.parse(file.read()) + + if not os.path.exists(FILE + "/archive.json"): + f = open(FILE + "/archive.json", "w") + f.write(JSON.stringify({"main": []})) + f.close() + + with open(f'{DIR}/archive.json', "r+") as ar_file: + archive = JSON.parse(ar_file.read()) + archive["main"].append(now) + ar_file.write(JSON.stringify(archive)) + +@main.command(aliases=["n"]) +def now(): + with open(f'{DIR}/now.json', "r") as file: + print(file.read()) + +@main.command() +def all(): + global data + print(JSON.stringify(data)) + +@main.command(aliases=["ea"]) +def edit_all(): + os.system(f'{EDITOR} {DIR}/main.json') + + +@main.command(aliases=["l"]) +def get_len(): + global data + print(len(data)) + +@main.result_callback() +def process_result(result, **kwargs): + global data + with open(FILE, "w") as file: + file.write(JSON.stringify(data)) + + +############################################################################# +# main + +if __name__ == "__main__": + + if not os.path.exists(DIR): + os.mkdir(DIR) + os.mkdir(DIR + "/files") + + if not os.path.exists(FILE): + f = open(FILE, "w") + f.write(JSON.stringify([])) + f.close() + + global data + with open(FILE, "r") as file: + data = JSON.parse(file.read()) + + main() + + + diff --git a/mybin/win b/mybin/win new file mode 100755 index 0000000..9c2decc --- /dev/null +++ b/mybin/win @@ -0,0 +1,3 @@ +#!/bin/bash + +~/work/config/scripts/win -o main-win 192.168.122.5 $@ diff --git a/scripts/nav/db b/scripts/nav/db new file mode 100644 index 0000000..543287c --- /dev/null +++ b/scripts/nav/db @@ -0,0 +1,5 @@ +* H ~ +* / / +~ w ~/work +~/work c config + diff --git a/scripts/nav/main.py b/scripts/nav/main.py new file mode 100644 index 0000000..3033f9d --- /dev/null +++ b/scripts/nav/main.py @@ -0,0 +1,58 @@ + +import shlex +from pathlib import Path +from os import path +import os + +DB_FILE = "/home/me/work/config/nav/db" + + +def main(): + pwd = Path(os.getcwd()) + db_matches = get_db_matches(pwd) + folder_matches = get_folder_matches(pwd) + + print(my_resolve("~/work/config/")) + print("db:", db_matches) + print("folder:", folder_matches) + + +def get_db_matches(directory): + matches = [] + with open(DB_FILE, "r") as file: + for line in file.readlines(): + tmp = shlex.split(line) + try: + dir_in = tmp[0] + shortcut = tmp[1] + dest = tmp[2] + except: + continue + + if dir_in == "*": + matches.append((shortcut, dest)) + if dir_in == "~": + #if directory == Path.home(): + matches.append((shortcut, dest)) + + return matches + +def get_folder_matches(directory): + matches = [] + ls = os.listdir(directory) + + return matches + +def my_resolve(path): + if str(path)[0] == "~": + path_as_list = list(str(path)) + path_as_list.pop(0) + print("path_as_list:", path_as_list) + return Path(str(Path.home()) + "".join(path_as_list)) + + return path.resolve() + + +if __name__ == "__main__": + main() + diff --git a/scripts/size.py b/scripts/size.py new file mode 100644 index 0000000..f0d17c9 --- /dev/null +++ b/scripts/size.py @@ -0,0 +1,17 @@ + +import sys + +s = 0 +for line in sys.stdin: + (val, unit) = line.split(" ") + val = float(val) + + if "MiB" in unit: + val *= 1000 + + s += val + +print("MB: ", round(s/1000)) +print("GB: ", round(s/1000000)) + + diff --git a/scripts/song b/scripts/song new file mode 100755 index 0000000..f56a595 --- /dev/null +++ b/scripts/song @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 + +# written while listening to mocking bird on loop +# if you really went through my config in that much detail... +# ... to stumble upon this weired script i wrote a long time ago +# ... please message me on discord (@c2vi) about it!! + +from datetime import datetime +import sys +import json +import requests +import base64 +import os + +with open("~/.mysecrets/spotify-client-id", "r") as file: + CLIENT_ID = file.read() +with open("~/.mysecrets/spotify-client-secret", "r") as file: + CLIENT_SECRET = file.read() + +LIST_COUNT = 6 +FILL_TO = 45 + +CONF_PATH = os.getenv("SONG_CONF_PATH") +if CONF_PATH == "": + print("No SONG_CONF_PATH environment variable found") + exit(1) + + +def get_token(): + url = "https://accounts.spotify.com/api/token" + form_data = {"grant_type": "client_credentials"} + + + message = CLIENT_ID + ":" + CLIENT_SECRET + message_bytes = message.encode('ascii') + base64_bytes = base64.b64encode(message_bytes) + auth_base64 = base64_bytes.decode('ascii') + + + headers = { + "user-agent": "Hi Spotify.....xD", + "Authorization": f"Basic {auth_base64}", + } + + x = requests.post(url, headers=headers, data=form_data) + + data = x.json() + return data["access_token"] + +def spotify_search(name): + token = get_token() + url = "https://api.spotify.com/v1/search" + + headers = { + "user-agent": "Hi Spotify.....xD", + "Authorization": f"Bearer {token}", + } + + params = {"q": name, "type": "track"} + + x = requests.get(url, headers=headers, params=params) + + data = x.json() + count = 0 + for track in data["tracks"]["items"]: + count += 1 + if count > LIST_COUNT: + break + + #print(track.keys()) + name = track["name"] + artists = get_artists(track) + + out = f"{count}) {name}" + out = fill(out) + out += f"BY: {artists}" + print(out) + + try: + number = int(input("NUMBER: ")) + return data["tracks"]["items"][number -1] + except: + exit(1) + +def get_artists(track): + artists = "" + for artist in track["artists"]: + if artists != "": + artists += " --- " + artist["name"] + else: + artists += artist["name"] + + return artists + +def add_track(track, pos = None): + # get the track id + # first letter , or first two, .... + count = 1 + myid = track["name"][0:count] + while get_track_pos(myid) != -1: + count += 1 + myid = track["name"][0:count] + + if count == 2000: + print("Count went to 2000 in add_track") + exit(1) + + mytrack = { + "id": track["id"], + "name": track["name"], + "artists": get_artists(track), + "myid": myid, + } + + if pos == None: + config["now"].append(mytrack) + else: + config["now"].insert(pos -1, mytrack) + + config["log"].append({ + "type": "add", + "track": mytrack, + "time": now.strftime("%m/%d/%Y-%H:%M:%S"), + }) + +def set_track(track_id, pos): + mytrack = get_track_from_myid(track_id) + old_pos = get_track_pos(track_id) + config["now"].pop(old_pos) + config["now"].insert(pos, mytrack) + + config["log"].append({ + "type": "move", + "track": mytrack, + "time": now.strftime("%m/%d/%Y-%H:%M:%S"), + "from": old_pos +1, + "to": pos +1, + }) + + +def get_track_pos(track_or_myid): + id = "" + if type(track_or_myid) == dict: + id = track_or_myid["myid"] + else: + id = track_or_myid + + count = 0 + for track in config["now"]: + if track["myid"] == id: + return count + + count += 1 + + return -1 + +def get_track_from_myid(myid): + for track in config["now"]: + if track["myid"] == myid: + return track + print(f"Track {myid} not found") + exit(1) + + +def remove_track(track_or_myid): + myid = "" + if type(track_or_myid) == dict: + myid = track_or_myid["myid"] + else: + myid = track_or_myid + + config["log"].append({ + "type": "remove", + "track": get_track_from_myid(myid), + "time": now.strftime("%m/%d/%Y-%H:%M:%S"), + }) + + new_tracks = [] + for track in config["now"]: + if track["myid"] != myid: + new_tracks.append(track) + + config["now"] = new_tracks + +def list_track(): + count = 0 + for track in config["now"]: + count += 1 + out = str(count) + ") " + track["myid"] + out = fill(out, l=10) + out += track["name"] + out = fill(out) + out += "BY: " + track["artists"] + print(out) + +def fill(string, l = FILL_TO): + count = 0 + while len(string) < l: + string += " " + count += 1 + return string + +def log(): + for entry in config["log"]: + typ = entry["type"] + name = entry["track"]["name"] + time = entry["time"] + if typ == "move": + fro = entry["from"] + to = entry["to"] + print(f"MOVE \t from {fro} to {to} \t {time} \t {name}") + + elif typ == "add": + print(f"ADD \t {time} \t {name}") + + elif typ == "remove": + print(f"REMOVE \t {time} \t {name}") + +def main(): + searh_term = " ".join(args[2:len(args)]) + if args[1] == "s": + track = spotify_search(searh_term) + + elif args[1] == "a" or args[1] == "add": + try: + pos = int(args[2]) + print("Inserting at pos:", pos) + searh_term = " ".join(args[3:len(args)]) + track = spotify_search(searh_term) + add_track(track, pos = pos) + except: + track = spotify_search(searh_term) + add_track(track) + + elif args[1] == "rm": + remove_track(args[2]) + + elif args[1] == "l": + list_track() + + elif args[1] == "st" or args[1] == "set": + set_track(args[2], int(args[3]) -1) + + list_track() + + elif args[1] == "up": + pos = get_track_pos(args[2]) + delta = 1 + try: + delta = int(args[3]) + except: + pass + + set_track(args[2], pos - delta) + list_track() + + elif args[1] == "down" or args[1] == "dn": + pos = get_track_pos(args[2]) + delta = 1 + try: + delta = int(args[3]) + except: + pass + + set_track(args[2], pos + delta) + list_track() + + elif args[1] == "log" and len(args) >= 3 and args[2] == "rm": + num = 1 + try: + num = int(args[3]) + except: + pass + + config["log"] = config["log"][0:-num] + log() + + elif args[1] == "log": + log() + + else: + print("Unknown command!") + exit(1) + +if __name__ == "__main__": + + args = sys.argv + + now = datetime.now() + + + # read config + with open(CONF_PATH, "r") as file: + config = json.loads(file.read()) + + # init config + if config.get("log", None) == None: + config["log"] = [] + + if config.get("now", None) == None: + config["now"] = [] + + main() + + # write config + with open(CONF_PATH, "w") as file: + file.write(json.dumps(config)) + + diff --git a/scripts/win b/scripts/win new file mode 100755 index 0000000..aec2050 --- /dev/null +++ b/scripts/win @@ -0,0 +1,155 @@ +#!/bin/bash + + +#default_vm_name=windp +#default_vm_uuid=12650dba-6232-40d8-9863-6c2bb267a0c9 + +#default_vm_name=tiny10 +#default_vm_uuid=6a412143-871f-4838-bacd-5dcfa5fa95c3 + +username=me +password=$(cat ~/.mysecrets/win-vm-pwd) + +if [ "$1" == "-o" ];then + cmd=$4 + default_vm_name=$2 + default_vm_uuid=$2 + default_vm_ip=$3 +else + cmd=$1 +fi + +#do stuff + +if [ "$cmd" == "st" ];then + sudo umount /home/sebastian/winwork + + #virsh -c qemu:///system attach-disk 12650dba-6232-40d8-9863-6c2bb267a0c9 /dev/nvme0n1 sdd --targetbus virtio --persistent + + virsh -c qemu:///system start $default_vm_uuid + + #sleep 30 + #sudo mount -t cifs //192.168.122.4/winwork /home/sebastian/winwork -o user=$username -o password=$password -o uid=1000 -o gid=1000 + + +elif [ "$cmd" == "h" ];then + sudo mount /home/sebastian/winwork + +elif [ "$cmd" == "c" ];then + virt-manager --connect qemu:///system --show-domain-editor $default_vm_uuid + +elif [ "$cmd" == "sm" ];then + sudo umount /home/sebastian/winwork + virsh -c qemu:///system managedsave $default_vm_uuid + +elif [ "$cmd" == "s" ];then + virsh -c qemu:///system domstate $default_vm_uuid + + +elif [ "$cmd" == "ld" ];then + virsh -c qemu:///system domblklist --domain $default_vm_uuid --details + echo ---------------------------------------- + virsh -c qemu:///system dumpxml $default_vm_uuid | grep sdd + + +elif [ "$cmd" == "w" ];then + virsh -c qemu:///system attach-disk $default_vm_uuid /dev/nvme0n1 sdd --targetbus virtio --persistent + sleep 0.5 + sudo mount -t cifs //$default_vm_ip/winwork /home/sebastian/winwork -o user=$username -o password=$password -o uid=1000 -o gid=1000 + +elif [ "$cmd" == "m" ];then + sudo mount -t cifs //$default_vm_ip/winwork /home/sebastian/winwork -o user=$username -o password=$password -o uid=1000 -o gid=1000 + +elif [ "$cmd" == "u" ];then + virsh -c qemu:///system attach-disk $default_vm_uuid /dev/nvme0n1 sdd --targetbus usb --persistent + sleep 0.5 + sudo mount -t cifs //$default_vm_ip/winwork /home/sebastian/winwork -o user=$username -o password=$password -o uid=1000 -o gid=1000 + + +elif [ "$cmd" == "uu" ];then + virsh -c qemu:///system detach-disk $default_vm_uuid /dev/nvme0n1 --persistent + sudo umount /home/sebastian/winwork + +elif [ "$cmd" == "uw" ];then + #sudo modprobe shpchp + #sudo modprobe acpiphp + virsh -c qemu:///system detach-disk $default_vm_uuid /dev/nvme0n1 --persistent + virsh -c qemu:///system shutdown $default_vm_uuid + +elif [ "$cmd" == "sp" ];then + virsh -c qemu:///system shutdown $default_vm_uuid + virsh -c qemu:///system shutdown $default_vm_uuid + virsh -c qemu:///system shutdown $default_vm_uuid + + #sleep 15 + + #virsh -c qemu:///system detach-disk $default_vm_uuid /dev/nvme0n1 --persistent + #sudo mount /home/sebastian/winwork + + + +elif [ "$cmd" == "p" ];then + sudo umount /home/sebastian/winwork + virsh -c qemu:///system suspend $default_vm_uuid + + #sleep 0.2 + #kill -SIGSTOP $(pgrep qemu) + + +elif [ "$cmd" == "up" ];then + #kill -SIGCONT $(pgrep qemu) + #sleep 0.2 + virsh -c qemu:///system resume $default_vm_uuid + + sleep 0.2 + sudo mount -t cifs //$default_vm_ip/winwork /home/sebastian/winwork -o user=$username -o password=$password -o uid=1000 -o gid=1000 + + +elif [ "$cmd" == "f" ];then + RDP_SCALE=100 + MULTI_FLAG="span" + RDP_USER=$username + RDP_PASS=$password + RDP_IP=$default_vm_ip + + xfreerdp ${RDP_FLAGS} /u:"${RDP_USER}" /p:"${RDP_PASS}" /v:${RDP_IP} /scale:${RDP_SCALE} /dynamic-resolution +clipboard +auto-reconnect +home-drive /wm-class:"Microsoft Windows" -grab-keyboard 1> /dev/null 2> /dev/null & + #xfreerdp ${RDP_FLAGS} /u:"${RDP_USER}" /p:"${RDP_PASS}" /v:${RDP_IP} /scale:${RDP_SCALE} /dynamic-resolution +clipboard +auto-reconnect +home-drive /wm-class:"Microsoft Windows" -grab-keyboard + # +elif [ "$cmd" == "fl" ];then + RDP_SCALE=100 + MULTI_FLAG="span" + RDP_USER=$username + RDP_PASS=$password + RDP_IP=$default_vm_ip + + xfreerdp ${RDP_FLAGS} /u:"${RDP_USER}" /p:"${RDP_PASS}" /v:${RDP_IP} /scale:${RDP_SCALE} /dynamic-resolution +clipboard +auto-reconnect +home-drive /wm-class:"Microsoft Windows" -grab-keyboard + +elif [ "$cmd" == "fup" ];then + #kill -SIGCONT $(pgrep qemu) + #echo cont + #sleep 0.2 + virsh -c qemu:///system resume $default_vm_uuid + + sleep 0.4 + sudo mount -t cifs //$default_vm_ip/winwork /home/sebastian/winwork -o user=$username -o password=$password -o uid=1000 -o gid=1000 + + sleep 0.2 + RDP_SCALE=100 + MULTI_FLAG="span" + RDP_USER=$username + RDP_PASS=$password + RDP_IP=$default_vm_ip + + xfreerdp ${RDP_FLAGS} /u:"${RDP_USER}" /p:"${RDP_PASS}" /v:${RDP_IP} /scale:${RDP_SCALE} /dynamic-resolution +clipboard +auto-reconnect +home-drive /wm-class:"Microsoft Windows" -grab-keyboard 1> /dev/null 2> /dev/null & + +elif [ "$cmd" == "l" ];then + looking-glass-client -m KEY_END + +fi + + + + + + +