[windows] skip 'skipping gpg tests on Windows'
[!exec:gpg] skip 'gpg not found in $PATH'

mkhomedir
mkgpgconfig

# test that chezmoi add --encrypt encrypts
cp golden/.encrypted $HOME
chezmoi add --encrypt $HOME${/}.encrypted
exists $CHEZMOISOURCEDIR/encrypted_dot_encrypted.asc
grep '-----BEGIN PGP MESSAGE-----' $CHEZMOISOURCEDIR/encrypted_dot_encrypted.asc

# test that chezmoi apply decrypts
rm $HOME/.encrypted
chezmoi apply --force
cmp golden/.encrypted $HOME/.encrypted

# test that chezmoi apply --exclude=encrypted does not apply encrypted files
rm $HOME/.encrypted
chezmoi apply --exclude=encrypted --force
! exists $HOME/.encrypted
chezmoi apply --force
cmp $HOME/.encrypted golden/.encrypted

# test that chezmoi detects gpg encryption if gpg is configured but encryption = "gpg" is not set
removeline $CHEZMOICONFIGDIR/chezmoi.toml 'encryption = "gpg"'
chezmoi cat $HOME${/}.encrypted
cmp stdout golden/.encrypted

# test that chezmoi decrypt decrypts stdin
stdin $CHEZMOISOURCEDIR${/}encrypted_dot_encrypted.asc
chezmoi decrypt
cmp stdout golden/.encrypted

# test that chezmoi decrypt decrypts a file
chezmoi decrypt $CHEZMOISOURCEDIR${/}encrypted_dot_encrypted.asc
cmp stdout golden/.encrypted

# test chezmoi encrypt/chezmoi decrypt round trip
chezmoi encrypt golden/.encrypted
stdout '-----BEGIN PGP MESSAGE-----'
stdin stdout
chezmoi decrypt
cmp stdout golden/.encrypted

# test that chezmoi edit --apply transparently decrypts and re-encrypts
chezmoi edit --apply --force $HOME${/}.encrypted
grep '# edited' $HOME/.encrypted

# test that chezmoi files in subdirectories can be encrypted and that suffix can be set
appendline $CHEZMOICONFIGDIR/chezmoi.toml '  suffix = ".gpg"'
mkdir $HOME/.dir
cp golden/.encrypted $HOME/.dir
chezmoi add --encrypt $HOME${/}.dir${/}.encrypted
grep '-----BEGIN PGP MESSAGE-----' $CHEZMOISOURCEDIR/dot_dir/encrypted_dot_encrypted.gpg
chezmoi edit --apply $HOME${/}.dir${/}.encrypted
grep '# edited' $HOME/.dir/.encrypted

# test that chezmoi edit strips the encrypted suffix
[!windows] env EDITOR=echo
[windows] env EDITOR=printargs
chezmoi edit $HOME${/}.dir${/}.encrypted
stdout '\.dir/\.encrypted\r?$'

-- bin/printargs.cmd --
@echo off
setlocal
set out=%*
set out=%out:\=%
echo %out%
endlocal
-- golden/.encrypted --
# contents of .encrypted
